Plotly Trace Graph绘制异常求助:复刻家庭储蓄水平条形图
解决建议
以下是完整的实现代码,同时针对你的三个需求逐一说明解决逻辑:
import plotly.express as px import pandas as pd # 你的数据集 data = [{'Year': 2020, 'Country': 'Austria', 'total_wealth': 1965.0672, 'total_savings': 53.364}, {'Year': 2020, 'Country': 'Belgium', 'total_wealth': 2701.08, 'total_savings': 56.856}, {'Year': 2020, 'Country': 'Denmark', 'total_wealth': 3292.4772, 'total_savings': 22.956}, {'Year': 2020, 'Country': 'Germany', 'total_wealth': 2071.3288, 'total_savings': 65.668}, {'Year': 2020, 'Country': 'Italy', 'total_wealth': 2500.7532, 'total_savings': 40.904}, {'Year': 2020, 'Country': 'Netherlands', 'total_wealth': 3180.148, 'total_savings': 75.328}, {'Year': 2020, 'Country': 'Sweden', 'total_wealth': 2747.4992, 'total_savings': 67.8}] df = pd.DataFrame(data) # 绘制水平条形图 fig = px.bar(df, y='Country', x='total_savings', orientation='h', color='total_savings', color_continuous_scale='Blues') # 添加条形旁的数值注释 fig.update_traces(text=df['total_savings'].round(2), textposition='outside', cliponaxis=False) # 调整x轴刻度,隐藏0刻度 min_savings = df['total_savings'].min() fig.update_layout( xaxis=dict( range=[min_savings - 5, df['total_savings'].max() + 5], tickmode='linear', dtick=10, title='Total Savings' ), yaxis=dict( title='Country', categoryorder='total ascending' ), coloraxis_showscale=False, title='Household Savings by Country (2020)', margin=dict(l=100, r=100) ) fig.show()
1. 贴近目标图的条形实现
- 用
orientation='h'生成水平条形,给color传total_savings设置蓝色渐变配色,匹配官网示例的视觉风格。 - 给y轴加
categoryorder='total ascending',让国家按储蓄值从小到大排列,和目标图的排序逻辑一致。 - 关闭颜色渐变条(
coloraxis_showscale=False),简化布局更贴近示例。
2. 添加条形旁的注释
- 通过
update_traces把text设为保留两位小数的储蓄值,textposition='outside'将注释放在条形外侧,cliponaxis=False确保数值不会被x轴截断。
3. 隐藏x轴0刻度
- 手动指定x轴范围:以最小储蓄值为基准,让x轴起始点略小于最小值、终点略大于最大值,0刻度自然不会出现在视图内。
- 设置
tickmode='linear'和dtick=10,让刻度间隔均匀,提升可读性。
内容的提问来源于stack exchange,提问作者Brie MerryWeather
相关产品推荐
相关产品推荐

