Django项目使用Plotly绘制柱状图单值柱形过宽问题如何解决
修复方案
你可以通过修改以下三类Plotly配置参数解决单条柱形过宽的问题:
- 柱形固定宽度参数:在
go.Bar中添加width参数,直接限制单根柱形的最大宽度,取值范围建议为0.1~0.8,可根据视觉效果调整。 - 全局柱间距参数:在layout配置中添加
bargap参数,设置柱形与x轴边界、柱形之间的间隙占比,取值范围为0~1,数值越大间隙越宽。 - x轴显示范围参数:在layout的xaxis配置中添加
range参数,可搭配动态逻辑适配不同数据量的显示需求,避免单条数据时柱形撑满整个画布。
修改后的参考代码如下:
def get_leads_data(request): c = Profile.objects.get(user=request.user) qs = Leads.objects.filter( agent_id=c,status='Open') df = read_frame(qs) graphs = [] graphs.append(go.Bar( x=df['company'], y=df['expected_revenue'], name='Estimated Revenue', width=0.5, # 新增:固定柱形宽度 )) layout={ 'title': 'Estimated Revenue by Company', 'xaxis_title':'Company', 'yaxis_title':'Revenue', 'height':500, 'width':640, 'bargap':0.4, # 新增:全局柱间隙占比 # 新增:动态适配x轴显示范围 'xaxis': { 'range': [-0.5, len(df)-0.5] if len(df) >1 else [-0.5, 1.5] } } plot_div = plot({'data': graphs, 'layout': layout}, output_type='div') return render(request,'account/plot.html',{'plot_div':plot_div})
内容的提问来源于stack exchange,提问作者Francisco Colina
相关产品推荐
相关产品推荐

