I'm using a plotly.express bar chart to visualize categorical data like this:
fig = px.bar(data, x='Algorithm', y='NDE', text_auto='.3f', color='Algorithm',
color_discrete_map={'Ensembling':'orange', 'CO':'blue', 'Mean':'blue', 'DAE':'blue',
'S2P':'blue', 'S2S':'blue', 'WinGru':'blue'})
fig.update_layout(barmode='stack', xaxis={'categoryorder':'total descending'})
fig.show()
Gives me this result:
However, that way of highlighting a specific bar in the chart seems somewhat "overengineered" to me.
So my question is: Does anyone know a more simple way to highlight one specific bar in a python plotly express bar chart?
Thanks for any suggestions! :-)
No need to be that explicit with color_discrete_map. You can define a default color and then overwrite. This still generates the same kind of color_discrete_map dictionary as in your example, but it's more robust.
import plotly.express as px
default_color = "blue"
colors = {"China": "red"}
data = px.data.gapminder().query("year == 1952")
color_discrete_map = {
c: colors.get(c, default_color)
for c in data.country.unique()}
fig = px.bar(data, x='country', y='pop', color='country',
color_discrete_map=color_discrete_map)
fig.update_traces(showlegend=False)
fig.show()
Related
I would like to add a second Y axis to my bar plot bellow, that is the number of citizens in integer:
this graph was made using plotly:
import plotly.express as px
fig = px.bar(df, x="country",y="pourcent_visit",color="city",barmode='group')
# fig.add_hline(y=10)
fig.show()
To my knowledge, there's no direct way to do this. But you can easily build a Plotly Express figure, grab the traces (and data structures) from there and combine them in a figure that allows multiple axes using fig = make_subplots(specs=[[{"secondary_y": True}]]). With no provided data sample, I'll use the built-in dataset px.data.tips() that I'm guessing to a large part resembles the structure of your real world dataset judging by the way you've applied the arguments in px.bar(). Details in the comments, but please don't hesitate to let me know if something is unclear.
Plot:
Complete code:
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# sample data
df = px.data.tips()
# figure setup with multiple axes
fig = make_subplots(specs=[[{"secondary_y": True}]])
# build plotly express plot
fig2 = px.bar(df, x="day", y="total_bill", color="smoker", barmode="group")
# add traces from plotly express figure to first figure
for t in fig2.select_traces():
fig.add_trace(t, secondary_y = False)
# handle data for secondary axis
df2 = df.groupby('day').agg('sum')#.reset_index()
df2 = df2.reindex(index = df['day'].unique()).reset_index()
#
fig.add_trace(go.Scatter(x = df2['day'], y = df2['size'], mode = 'lines'), secondary_y = True)
# fix layout
fig.update_layout(legend_title_text = 'smoker')
fig.show()
I am using plotly express and I want to display some data:
import plotly.express as px
dfx = px.data.tips()
fig = px.scatter(dfx,
x='total_bill', y='tip',
color='size',
template='plotly_dark',
range_color=[2,4])
My goal is to update the range color after it has been defined.
I tried something like this:
fig.update_layout(range_color=[3,6])
ValueError: Invalid property specified for object of type plotly.graph_objs.Layout: 'range'
but without success.
Are you aware of what I need to write in order to update the range color values?
To change the range of the color bar, you would change the maximum and minimum values of the color axis. This is different from the description of the graph settings, which can be found in fig.layout.
import plotly.express as px
dfx = px.data.tips()
fig = px.scatter(dfx,
x='total_bill', y='tip',
color='size',
template='plotly_dark',
range_color=[2,4])
fig.update_layout(coloraxis=dict(cmax=6, cmin=3))
fig.show()
I think you need to use range_color in the px.scatter function
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df,
x="sepal_width",
y="sepal_length",
color="sepal_length",
color_continuous_scale=["red",
"green", "blue"])
fig.show()
Here is a link to the documentation plotly
You can also look here at fig.update_coloraxes
update coloraxes
Also just found this in the documentation for update_layout
fig.update_layout(colorscale=dict(...))
update colorscale
Hi I am trying to use plotly to create a 100% stacked bar chart in streamlit using plotly. I tried using relative but to no avail.
dfCategory = dfQuery.groupby(['l1_category_name','pricingPosition'])['pricingPosition'].count().reset_index(name="count")
fig = px.bar(dfCategory, x="count", y="l1_category_name", color='pricingPosition', orientation='h',
height=400)
fig.update_layout(barmode='relative')
st.plotly_chart(fig, use_container_width=True)
Any help would be greatly appreciated
I think the 'relative' mode in Plotly is a function to summarize positive and negative, not a display in percentages. The histogram function has the ability to stack percentages, which can also be displayed as percentages. Here is an example from the official reference.
import plotly.express as px
long_df = px.data.medals_long()
fig = px.bar(long_df, x="nation", y="count", color="medal", title="Long-Form Input")
fig.update_layout(barmode='relative')
fig.show()
import plotly.express as px
long_df = px.data.medals_long()
fig = px.histogram(long_df, x="nation",
y="count", color="medal",
barnorm='percent', text_auto='.2f',
title="Long-Form Input")
fig.show()
I am trying to plot a subplot which contains 14 candlestick charts of cryptocurrency data. (
https://www.kaggle.com/c/g-research-crypto-forecasting)
However, it seems that it can't display the figure properly.
Here is my code:
from plotly import subplots
import plotly.graph_objects as go
fig = subplots.make_subplots(rows=7,cols=2)
for ix,coin_name in enumerate(asset_details["Asset_Name"]):
coin_df = crypto_df[crypto_df["Asset_ID"]==asset_names_dict[coin_name]].set_index("timestamp")
coin_df_mini = coin_df.iloc[-100:]
column = lambda ix: 1 if ix % 2 == 0 else 2
candlestick = go.Candlestick(x=coin_df_mini.index, open=coin_df_mini['Open'], high=coin_df_mini['High'], low=coin_df_mini['Low'], close=coin_df_mini['Close'])
fig = fig.add_trace(candlestick, row=((ix//2) + 1), col=column(ix))
fig.update_layout(xaxis_rangeslider_visible=False)
fig.update_layout(title_text="Candlestick Charts", height=2800)
fig.show()
And here is the problem:
rangeslider_problem
No matter I plot the figure with or without the rangeslider, it's always out of shape.
You need to hide the slider on the x-axis unit created in the subplot. My answer was to do all the subplots manually. I don't have time to deal with this right now, but there is also a way to update the output content in a loop process.
fig.update_layout(xaxis1=dict(rangeslider=dict(visible=False)),
xaxis2=dict(rangeslider=dict(visible=False)),
xaxis3=dict(rangeslider=dict(visible=False)),
xaxis4=dict(rangeslider=dict(visible=False)),
xaxis5=dict(rangeslider=dict(visible=False)),
xaxis6=dict(rangeslider=dict(visible=False)),
xaxis7=dict(rangeslider=dict(visible=False)),
xaxis8=dict(rangeslider=dict(visible=False)),
xaxis9=dict(rangeslider=dict(visible=False)),
xaxis10=dict(rangeslider=dict(visible=False)),
xaxis11=dict(rangeslider=dict(visible=False)),
xaxis12=dict(rangeslider=dict(visible=False)),
xaxis13=dict(rangeslider=dict(visible=False)),
xaxis14=dict(rangeslider=dict(visible=False)),
)
I'm making a line chart below. I want to make the lines colored by a variable Continent. I know it can be done easily using plotly.express
Does anyone know how I can do that with plotly.graph_objects? I tried to add color=gapminder['Continent'], but it did not work.
Thanks a lot for help in advance.
import plotly.express as px
gapminder = px.data.gapminder()
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Scatter(x=gapminder['year'], y=gapminder['lifeExp'],
mode='lines+markers'))
fig.show()
Using an approach like color=gapminder['Continent'] normally applies to scatterplots where you define categories to existing points using a third variable. You're trying to make a line plot here. This means that not only will you have a color per continent, but also a line per continent. If that is in fact what you're aiming to do, here's one approach:
Plot:
Code:
import plotly.graph_objects as go
import plotly.express as px
# get data
df_gapminder = px.data.gapminder()
# manage data
df_gapminder_continent = df_gapminder.groupby(['continent', 'year']).mean().reset_index()
df = df_gapminder_continent.pivot(index='year', columns='continent', values = 'lifeExp')
df.tail()
# plotly setup and traces
fig = go.Figure()
for col in df.columns:
fig.add_trace(go.Scatter(x=df.index, y=df[col].values,
name = col,
mode = 'lines'))
# format and show figure
fig.update_layout(height=800, width=1000)
fig.show()