You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 10:08:21