0

I'm trying to group traces of a barchart and maintain the same distance between each group.

import pandas as pd
import plotly.express as px

df = pd.DataFrame({
  "City": ["Toronto", "Toronto", "Toronto", "CPH", "CPH", "London", "London"],
  "Tower name": ["T1", "T2", "T3", "T4", "T5", "T6","T7"],
  "Height": [1.0, 1.5, 2.0, 3.0, 4.0, 2.0 ,5.0],
})

fig = px.bar(x=df['City'], y=df['Height'],color = df['Tower name'], color_discrete_sequence=['black'])
fig.update_layout(showlegend=False)
fig.update_layout(barmode='group')
fig.show()

The result is as shown below. Result

The solution I want is like this

Desired Result

I have found this thread but the solution in that thread suggest stacking the bars, which is not a possibility in my case.

Timo
  • 103
  • 5

1 Answers1

2

You can use multiple-categorical axes https://plotly.com/python/categorical-axes/#multicategorical-axes

go.Figure(go.Bar(x=df.loc[:,["City", "Tower name"]].T.values, y=df["Height"].values, marker_color="black"))

enter image description here

Rob Raymond
  • 29,118
  • 3
  • 14
  • 30
  • This is exactly what I was after. Thank you. A follow-up question: Would it be possible to remove the T1, T2, T3... etc marks and rotate the Toronto, CPH, London to be vertical when they get too close to each other (my real data set is significantly larger) – Timo Oct 29 '21 at 09:13
  • there are multiple restrictions on multi-category. this technique https://plotly.com/python/tick-formatting/#tickmode--array does not work for getting rid of T1,T2,... – Rob Raymond Oct 29 '21 at 09:36
  • Thank you rob. I have created a follow up question in a separate post: https://stackoverflow.com/questions/69767008/how-do-i-show-only-the-category-tick-and-rotate-them-of-a-multicategory-plotly – Timo Oct 29 '21 at 10:01