Plotly Express分组柱状图Y轴统一及标注字体调整问题
问题分析与解决方法
问题1:Y轴刻度不统一、柱子高度不符合数值逻辑
原因
你的Average revenue列在DataFrame中是字符串类型(数据里的数值用引号包裹),Plotly会将字符串视为分类数据而非数值数据,导致Y轴无法按数值大小排序,柱子高度也不会对应真实数值。
解决方法
将Average revenue列转换为数值类型(整数):
df['Average revenue'] = df['Average revenue'].astype(int)
问题2:柱子上方标注字体过小,update_layout调整无效
原因
柱子的文本标注属于trace层面的属性,而非layout属性,所以用update_layout()无法修改,需要通过update_traces()来设置textfont参数。
解决方法
在update_traces()中添加textfont参数,指定字体大小:
fig.update_traces(textposition='outside', textfont=dict(size=12))
修改后的完整代码
import pandas as pd df=pd.DataFrame([['C-1','C-11','111'],['C-1','C-12','121'],['C-1','C-13','31'],['C-1','C-14','120'],['C-1','C-15','100'], ['C-2','C-21','150'],['C-2','C-22','168'],['C-2','C-23','173'],['C-2','C-24','111'],['C-2','C-25','121'], ['C-3','C-31','123'],['C-3','C-32','100'],['C-3','C-33','111'],['C-3','C-34','111'],['C-3','C-35','163'], ['C-4','C-41','174'],['C-4','C-42','174'],['C-4','C-43','173'],['C-4','C-44','135'],['C-4','C-45','102'], ['C-5','C-51','118'],['C-5','C-52','122'],['C-5','C-53','113'],['C-5','C-54','178'],['C-5','C-55','142'] ],columns=['Case group','Case number','Average revenue']) # 转换为数值类型 df['Average revenue'] = df['Average revenue'].astype(int) import plotly.express as px fig = px.bar(df, x='Case number',y='Average revenue', color='Case group', barmode='group',text="Average revenue", height=500,width=700, color_discrete_sequence=[px.colors.qualitative.Dark2[0],px.colors.qualitative.Set2[1],px.colors.qualitative.Pastel[0],px.colors.qualitative.Set2[5],px.colors.qualitative.Set2[4],]) # 设置文本标注位置和字体大小 fig.update_traces(textposition='outside', textfont=dict(size=12)) fig.show()
内容的提问来源于stack exchange,提问作者MattD626
相关产品推荐
相关产品推荐

