Add two texts to each bar chart in plotly - python

I am working on plotly (python) to plot a horizontal bar chart like the below figure.
import plotly.express as px
fig = px.bar(
x=prices,
y=['Average $' + str(round(avg_price, 2)), 'Lowest $' +
str(round(min_price, 2)), 'Last $' + str(round(last_price, 2)),
'Proposed $' + str(round(proposed_price, 2))],
color=['Last', 'Average', 'Lowest', 'Proposed'],
text=delta,
orientation='h',
height=400,
)
fig.add_vline(x=spend[-1], line_width=2, line_dash="dash",
line_color="red")
fig.add_vline(x=max(spend), line_width=2, line_dash="dash",
line_color="green")
fig.update_traces( textposition='outside')
fig.update_layout(
title="Saving/Loss diagram",
xaxis_title="",
yaxis_title="",
legend_title="Vendor names",
width=1000,
)
fig.show()
In this figure I display text only outside of each bar chart. But now I am going to display another text inside each bar chart. How can I do that in plotly (python)?

If you want to add a text inside the bars with plotly.express, you could use fig.update_traces with two parameters texttemplate and textposition
You could try this code:
import plotly.express as px
data_canada = px.data.gapminder().query("country == 'Canada'")
fig = px.bar(data_canada, x='year', y='pop')
fig.update_traces(texttemplate = data_canada.year.unique(),textposition = "inside")
fig.show()
There is an option to do all this with plotly.graph_objects.
But here, you should add text that appears inside the bars and textposition adjust the text.
import plotly.graph_objects as go
data_canada = px.data.gapminder().query("country == 'Canada'")
fig = go.Figure(data=[go.Bar(
x=data_canada.year, y=data_canada["pop"],
text=data_canada.year.unique(),
textposition='inside'
)])
fig.show()
Update based on the comments:
You can change the position of each text for each bar but the possible positions are four positions: "inside" | "outside" | "auto" | "none" as documented on the main page of plotly here, search for textposition attribute.
To do this you can do it as follows:
import plotly.express as px
x = ['Aaron', 'Bob', 'Chris','Tom','Anna']
y = [5, 10, 6, 11, 8]
texts = ["first","second","third","fourth","fifth"]
positions = ['inside','outside','auto','outside','inside']
fig = px.bar(x=x, y=y)
fig.update_traces(texttemplate = texts, textposition = positions)
fig.show()

Related

Plotly: How to display the total sum of the values at top of a stacked bar chart along with the individual bar values?

I am trying to add the total at the top of the each stacked bar along with the individual bar values in Plotly Express in Python.
import plotly.express as px
df = px.data.medals_long()
fig = px.bar(df, x="medal", y="count", color="nation", text_auto=True)
fig.show()
This gives the below result
However I want the chart as below:
Although it can be annotated as a string, the easiest way is to add a graph in the text mode of a scatter plot.
import plotly.express as px
import plotly.graph_objects as go
df = px.data.medals_long()
dfs = df.groupby('medal').sum()
fig = px.bar(df, x="medal", y="count", color="nation", text_auto=True)
fig.add_trace(go.Scatter(
x=dfs.index,
y=dfs['count'],
text=dfs['count'],
mode='text',
textposition='top center',
textfont=dict(
size=18,
),
showlegend=False
))
fig.update_yaxes(range=[0,50])
fig.show()

How to specify the x coordinate on a grouped bar chart on plotly?

I made a bar chart with python plotly, and I want to put a marker on a particular bar, example non-smoking females.
Does anyone know how to specify this?
I took an example from the plotly documentation, if I try to put the marker it just takes the center of the main category.
import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="sex", y="total_bill",
color='smoker', barmode='group',
height=400)
#trying to set the marker
fig.add_trace(
go.Scatter(x=["Female"],
y=[1100]
))
fig.show()
inspired by this: https://community.plotly.com/t/grouped-bar-charts-with-corresponding-line-chart/19562/4
use xaxis2, work out position, have hardcoded it, but 0.15 has relationship to number of traces in bargoup and x value
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
df = px.data.tips()
fig = px.histogram(
df, x="sex", y="total_bill", color="smoker", barmode="group", height=400
)
# trying to set the marker
fig.add_trace(
go.Scatter(
x=[0.15],
y=[1100],
customdata=[["No", "Female"]],
xaxis="x2",
hovertemplate="smoker=%{customdata[0]}<br>sex=%{customdata[1]}<br>sum of total_bill=%{y}<extra></extra>",
)
)
fig.update_layout(xaxis2={"overlaying": "x", "range": [0, 1], "showticklabels": False})
fig

Adding caption below Python Plotly Choropleth Map

I want to add a caption below my plotly choropleth Map (using Python). I've looked into using annotations with graph_objs, but it only seems to work for locations within the map area. Is there a way to make the annotations show up below the choropleth map and/or is there an alternative way of doing this?
Right now I'm getting this but would like the caption to appear below the map area:
I've tried inputting y values less than 0, but then the text annotations just don't show up at all.
Here's my code:
import plotly.graph_objects as go
import pandas as pd
import plotly
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
fig = go.Figure(data=go.Choropleth(
locations = df['CODE'],
z = df['GDP (BILLIONS)'],
text = df['COUNTRY'],
colorscale = 'Blues',
autocolorscale=False,
reversescale=True,
marker_line_color='darkgray',
marker_line_width=0.5,
colorbar_tickprefix = '$',
colorbar_title = 'GDP<br>Billions US$',
))
fig.update_layout(
title_text='2014 Global GDP',
geo=dict(
showframe=False,
showcoastlines=False,
projection_type='equirectangular'
),
annotations = [dict(
x=0.5,
y=0, #Trying a negative number makes the caption disappear - I'd like the caption to be below the map
xref='paper',
yref='paper',
text='Source: <a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">\
CIA World Factbook</a>',
showarrow = False
)]
)
fig.show()
Setting y=-0.1 works fine on my end:
Plot 1
If that for some reason is not the case on your end (perhaps a version issue?), you should try to just leave it at y=0 and rather make room below the figure utself by adjustin the margins of the plot like this:
fig.update_layout(
margin=dict(l=20, r=20, t=60, b=20),
paper_bgcolor="LightSteelBlue")
Plot 2:
Complete code:
import plotly.graph_objects as go
import pandas as pd
import plotly
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
fig = go.Figure(data=go.Choropleth(
locations = df['CODE'],
z = df['GDP (BILLIONS)'],
text = df['COUNTRY'],
colorscale = 'Blues',
autocolorscale=False,
reversescale=True,
marker_line_color='darkgray',
marker_line_width=0.5,
colorbar_tickprefix = '$',
colorbar_title = 'GDP<br>Billions US$',
))
fig.update_layout(
title_text='2014 Global GDP',
geo=dict(
showframe=False,
showcoastlines=False,
projection_type='equirectangular'
),
annotations = [dict(
x=0.5,
y=0, #Trying a negative number makes the caption disappear - I'd like the caption to be below the map
xref='paper',
yref='paper',
text='Source: <a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">\
CIA World Factbook</a>',
showarrow = False
)]
)
fig.update_layout(
margin=dict(l=20, r=20, t=60, b=20),
paper_bgcolor="LightSteelBlue")
fig.show()

plotly: How to add text to existing figure?

Is it possible to add some text on the same html file as my plotly graph?
For example :
This is the code that generates a graph :
data = pd.read_csv('file.csv')
data.columns = ['price', 'place', 'date']
fig = px.scatter(data, x = "place", y = "price", )
fig.write_html("done.html")
This graph will generate a pyplot graph in an html file and I want to add some simple text (such as a conclusion line explaning the graph) under the graph.
This is an example of the output I would like:
ly
You can use fig.update_layout(margin=dict()) to make room for an explanation, and then fig.add_annotation() to insert any text you'd like below the figure utself to get this:
Complete code:
import plotly.graph_objects as go
import numpy as np
x = np.arange(-4,5)
y=x**3
yticks=list(range(y.min(), y.max(), 14))
#yticks.append(y.max())9
# build figure
fig = go.Figure(data=go.Scatter(x=x, y=y))
# make space for explanation / annotation
fig.update_layout(margin=dict(l=20, r=20, t=20, b=60),paper_bgcolor="LightSteelBlue")
# add annotation
fig.add_annotation(dict(font=dict(color='yellow',size=15),
x=0,
y=-0.12,
showarrow=False,
text="A very clear explanation",
textangle=0,
xanchor='left',
xref="paper",
yref="paper"))
fig.show()

Plotly express color bar argument missing go.Bar

import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x=“sepal_width”, y=“sepal_length”, color=“species”)
fig.show()
If I want to write the same code in plotly.graph_objects , than how I can include the color argument without using for loop. Basically I want to use bar and line chart in same axis with bar having a color code based on a different variable and pass that as a return in Dash.
bars =
for label, label_df in df.groupby(‘label’):
bars.append(go.Bar(x=label_df.x, y=label_df.y, name=label, marker={‘color’: colors[label]}))
trace1 = bars
trace2 = go.Scatter(x=label_df.x, y=label_df.y, name=‘Nifty 50’, mode=‘lines+markers’)
fig = go.Figure(data=[trace1])
fig.show()
You can use list comprehension:
Update:
df = px.data.iris()
trace1 = [go.Scatter(x=label_df.sepal_width,
y=label_df.sepal_length,
name=label,
mode='markers')
for label, label_df in df.groupby('species')]
fig = go.Figure(data=trace1)

Categories

Resources