This is how I do it:
To change bar gap : fig.update_traces(width=0.4)
import plotly.graph_objects as go
import plotly.express as pc
from plotly.subplots import make_subplots
import pandas as pd
#
data = {
'Cat': ['Cat A', 'Cat B', 'Cat C', 'Cat A', 'Cat B', 'Cat C'],
'Group': ['Group A', 'Group A', 'Group A', 'Group B', 'Group B', 'Group B'],
'Value': [10, 15, 20, 25, 30, 35]
}
df = pd.DataFrame(data)
# Define unique groups
unique_groups = df['Group'].unique()
n_groups = len(unique_groups)
#create color map
color_map= dict(
zip(
unique_groups, px.colors.qualitative.Set3[:n_groups]
)
)
#create subplots
fig = make_subplots(
rows=1,
cols=len(unique_groups),
shared_yaxes=True,
shared_xaxes=True,
horizontal_spacing=0,
x_title='x_axis',
y_title='y_axis' # Updated to 'y_axis'
)
#loop through groups and add them as subplots
for index, group in enumerate(unique_groups):
col_number = index + 1
fig.append_trace(go.Bar(
x=df[df['Group'] == group]['Cat'],
y=df[df['Group'] == group]['Value'],
marker_color=color_map[group],
name=group
), row=1, col=col_number)
fig.update_traces(width=0.4)
for i in range(1, n_groups + 1):
axis_name = f'yaxis{i}' if i == 1 else f'yaxis{i}'
fig.update_layout({
axis_name: dict(
showgrid=True,
gridcolor='rgba(0, 0, 0, 0.3)'
)
})
fig.update_layout(
plot_bgcolor='rgba(0,0,0,0)',
#paper_bgcolor='rgba(0,0,0,0)' #transparent background
)
#fig.write_image("fig1.png", scale=3)
fig.show()
Or I use the histogram without the histfunc when suitable:
import plotly.express as px
import pandas as pd
groups = ['Group A', 'Group A', 'Group A', 'Group B', 'Group B', 'Group B']
years = [2019, 2020, 2021, 2019, 2020, 2021]
values = [45, 60, 75, 30, 55, 70]
data = {'Group': groups, 'Year': years, 'Value': values}
dff = pd.DataFrame(data)
fig = px.histogram(dff, x='Group', y='Value', color='Year',
barmode='group', histfunc=None,
color_discrete_sequence=px.colors.qualitative.Set3,
category_orders={'Group': ['Group A', 'Group B']}
)
fig.update_layout(
plot_bgcolor='rgba(0,0,0,0)',
#paper_bgcolor='rgba(0,0,0,0)' #transparent background
)
fig.update_yaxes(gridcolor='rgba(0, 0, 0, 0.3)')
fig.show()