如何移除Plotly Express分组柱状图空柱,保证各组视觉间距相等
解决方案
Plotly默认的group柱状图模式会为所有颜色类别统一预留位置,因此柱子数量少的分组会出现空白间隙。可以通过手动计算每个柱子的坐标实现预期效果,以下是可直接运行的代码:
import pandas as pd import plotly.graph_objects as go 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 = go.Figure() # 可自定义调整的参数 bar_width = 0.25 # 单根柱子宽度 city_spacing = 0.6 # 不同城市之间的间距 current_x = 0 x_tick_pos = [] x_tick_label = [] # 按城市分组遍历绘制 for city, city_df in df.groupby("City", sort=False): # 记录当前城市标签的居中位置 center_x = current_x + (len(city_df)-1)*bar_width/2 x_tick_pos.append(center_x) x_tick_label.append(city) # 绘制当前城市下所有塔的柱子 for _, row in city_df.iterrows(): fig.add_trace(go.Bar( x=[current_x], y=[row["Height"]], width=bar_width, marker_color="black", showlegend=False )) current_x += bar_width # 城市之间添加固定间距 current_x += city_spacing # 配置X轴显示城市标签 fig.update_xaxes( tickvals=x_tick_pos, ticktext=x_tick_label, showgrid=False ) fig.show()
运行上述代码即可得到每个城市内柱子紧密排列、城市间间距完全一致的柱状图,匹配预期的展示效果。如果需要调整间距或者柱子宽度,直接修改对应参数即可。
内容的提问来源于stack exchange,提问作者Timo
相关产品推荐
相关产品推荐

