plotly separation with many bin - python

Given grouped bins , is there a way of having a larger gap between the bins? in
I.e, in the desired output, every bar/bar group has a predefined space around it.
# Change the default stacking
import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x="sex", y="total_bill",
color='smoker', barmode='group',
height=400)
fig.show()

After building a figure you can adjust the gap between the bars like this:
fig.layout.bargap = 0.8
I've used 0.8 just to clearly illustrate the effects, but that number can be set to any int or float in the interval [0, 1]
Complete code:
import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x="sex", y="total_bill",
color='smoker', barmode='group',
height=400)
f = fig.full_figure_for_development(warn=False)
fig.layout.bargap = 0.8
fig.show()

Related

How to add a secondary Y axis to a Plotly Express bar plot?

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()

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

python plotly area chart with Y-axis in percent

i try to plot the y-axis in percent. i there a way like in excel, excel scale automacily from 0 -100% ? or it is necessary first to calculate (group by year and continent) in the dataframe?
import plotly.express as px
df = px.data.gapminder()
fig = px.area(df, x="year", y="pop", color="continent",
line_group="country")
fig.show()
thanks for helP!
try this:
import plotly.express as px
df = px.data.gapminder()
dfw = df.groupby(['continent','year'])['pop'].sum().to_frame()
dfw.reset_index(inplace=True)
fig = px.area(dfw, x="year", y="pop", color="continent", groupnorm='fraction')
fig.update_layout(yaxis_tickformat='%')
fig.show()

Changing the within-group order of a grouped bar plot in plotly

I'd like to change the order of my within-group variable in a plotly bar plot in Python.
For example, how can I switch the order of lunch and dinner here?
import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x='sex', y='total_bill', color='time', barmode='group')
fig.show()
categoryorder can only change the order of groups, i.e. Male and Female.
Sort the df in descending order basis the column time.
import plotly.express as px
df = px.data.tips()
df.sort_values(['time'],ascending=[False],inplace=True)
fig = px.bar(df, x='sex', y='total_bill', color='time', barmode='group')
fig.show()
OUTPUT:

Categories

Resources