Plotly-Python中如何为同一分类下的两组柱状图添加间隔?
解决Plotly柱状图分类下方法组间添加间隔的问题
要实现每个分类(names)下两组方法(method one、method two)的柱状图之间的间隔,你可以通过以下两种方式解决:
方法一:使用offsetgroup配合间隔参数
给不同方法组的trace分配独立的offsetgroup,再通过bargroupgap控制组间间隔,bargap控制同组内柱子的间隔。修改后的代码如下:
import numpy as np import plotly.graph_objects as go values1 = abs(np.random.normal(0.5, 0.3, 13)) values2 = abs(np.random.normal(0.5, 0.3, 13)) values3 = abs(np.random.standard_normal(13)) values4 = abs(np.random.standard_normal(13)) names = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'] fig = go.Figure() # Method One 两个trace共用offsetgroup fig.add_trace(go.Bar( x=names, y=values1, legendgroup="group", legendgrouptitle_text="method one", name="first", offsetgroup="g1" )) fig.add_trace(go.Bar( x=names, y=values2, legendgroup="group", name="second", offsetgroup="g1" )) # Method Two 两个trace共用另一个offsetgroup fig.add_trace(go.Bar( x=names, y=values3, legendgroup="group2", legendgrouptitle_text="method two", name="first", offsetgroup="g2" )) fig.add_trace(go.Bar( x=names, y=values4, legendgroup="group2", name="second", offsetgroup="g2" )) # 调整间隔参数 fig.update_layout( barmode='group', bargap=0.1, # 同方法内两个柱子的间隔 bargroupgap=0.2 # 不同方法组之间的间隔 ) fig.update_traces(texttemplate='%{y:.2f}', textposition='inside') fig.show()
原代码中offsetgroup未生效的原因
未指定offsetgroup时,Plotly会默认将所有x轴相同的bar归为同一组。仅设置offsetgroup但未配合bargroupgap参数调整组间间隔,不会直观显示出分组效果。
方法二:重构x轴为复合分类
将x轴设置为(分类名, 方法名)的元组结构,让每个分类下自动生成两个方法分组,自然形成间隔:
import numpy as np import plotly.graph_objects as go values1 = abs(np.random.normal(0.5, 0.3, 13)) values2 = abs(np.random.normal(0.5, 0.3, 13)) values3 = abs(np.random.standard_normal(13)) values4 = abs(np.random.standard_normal(13)) names = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'] # 构造复合x轴,每个分类对应两个方法 x_method1 = [(name, "method one") for name in names] x_method2 = [(name, "method two") for name in names] fig = go.Figure() fig.add_trace(go.Bar( x=x_method1, y=values1, legendgroup="group", legendgrouptitle_text="method one", name="first" )) fig.add_trace(go.Bar( x=x_method1, y=values2, legendgroup="group", name="second" )) fig.add_trace(go.Bar( x=x_method2, y=values3, legendgroup="group2", legendgrouptitle_text="method two", name="first" )) fig.add_trace(go.Bar( x=x_method2, y=values4, legendgroup="group2", name="second" )) fig.update_layout(barmode='group') fig.update_traces(texttemplate='%{y:.2f}', textposition='inside') fig.show()
内容的提问来源于stack exchange,提问作者TheArtilleryGuy1
相关产品推荐
相关产品推荐

