如何在Python的Plotly中设置横向条形图并添加Y轴自定义标签
解决方法
1. 转为横向条形图
要实现逆时针旋转90度的横向条形图,只需对每个go.Bar trace做两处修改:
- 交换
x和y参数:将分类数据months移到y参数,数值数据移到x参数 - 添加
orientation='h'属性指定条形图为横向
2. 添加数值轴自定义标签
原代码中的数值轴(Y轴)在转为横向后变为X轴,可通过fig.update_layout()中的xaxis_title设置自定义轴标签;如果需要给分类轴(现在是Y轴)添加标签,也可设置yaxis_title。
修改后的完整代码
import plotly.graph_objects as go months = ["ABC","XYZ"] fig = go.Figure() fig.add_trace(go.Bar( y=months, x=[3.95,4.04], name='SMD', marker_color='yellow', orientation='h' )) fig.add_trace(go.Bar( y=months, x=[3.78,4.06], name='Camrest', marker_color='black', orientation='h' )) fig.add_trace(go.Bar( y=months, x=[4.16,4.28], name='MWOZ 2.1', marker_color='cadetblue', orientation='h' )) fig.update_layout( barmode='group', template="plotly_white", xaxis_title="自定义数值轴标签", # 原Y轴(数值)的自定义标签 yaxis_title="月份" # 可选:给分类轴添加标签 ) fig.show()
内容的提问来源于stack exchange,提问作者Soumya Ranjan Sahoo
相关产品推荐
相关产品推荐

