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

Python matplotlib绘制条形图:设置黄色柱y轴起始位置及右侧箭头

解决代码及修改说明

核心修改点

  • 针对Profit条形起始位置问题:调用bar()绘制黄色利润条时传入bottom=ausgaben参数,指定条形从支出数值的y坐标开始绘制,同时同步修正利润值标签的垂直位置,避免标签错位。
  • 针对右侧黄色箭头问题:使用annotate()方法绘制箭头,设置箭头颜色和利润条一致,箭头两端对齐两条水平参考线的高度,同时调整坐标轴右边界避免箭头被截断,将百分比标签移动到箭头旁匹配参考图样式。

修改后完整可运行代码

import matplotlib.pyplot as plt

ausgaben = 130386
einnahmen = 147233
profit = einnahmen - ausgaben

titles = ["Ausgaben", "Profit", "Einnahmen"]
euros = [ausgaben, profit, einnahmen]

colors = ['#6F8CA7', '#F6BC06', '#59908F']
dummysum1 = []
dummysum2 = []

for i in range(len(euros)):
    dummysum1.append(euros[i] + 4000)
    dummysum2.append(max(euros) + 15000)
# 修正利润标签位置:从ausgaben位置开始计算偏移
if euros[1] > 0:
    dummysum1[1] = ausgaben + euros[1] + 4000
if euros[1] <= 0:
    dummysum1[1] = 4000

position1 = (euros[0] + einnahmen) / 2

percentile = (einnahmen - ausgaben) / ausgaben * 100

if percentile > 0:
    label0 = '+{:.1f}%'.format(percentile)
else:
    label0 = '{:.1f}%'.format(percentile)

fig, ax = plt.subplots(figsize=(7, 5))
fig.set_facecolor('#D0A210')
fig.patch.set_alpha(0.2)
ax.bar(titles[0], euros[0], alpha=0.6, color=colors[0])
# 给利润条加bottom参数,指定从ausgaben高度开始绘制
ax.bar(titles[1], euros[1], bottom=ausgaben, alpha=0.6, color=colors[1])
ax.bar(titles[2], euros[2], alpha=0.6, color=colors[2])
plt.axhline(y=euros[0], color='#BCBCBC')
plt.axhline(y=einnahmen, color='#BCBCBC')

# 绘制右侧黄色箭头
ax.annotate(
    '', 
    xy=(2.7, einnahmen), 
    xytext=(2.7, ausgaben),
    arrowprops=dict(facecolor=colors[1], edgecolor=colors[1], shrink=0.03)
)

ax.set_facecolor('#D0A210')
ax.patch.set_alpha(0.02)

# 调整x轴范围,给右侧箭头和标签留出显示空间
ax.set_xlim(-0.5, 3.2)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)

ax.spines.right.set_visible(False)
ax.spines.left.set_visible(False)
ax.spines.top.set_visible(False)
ax.spines.bottom.set_visible(False)

ax.text(titles[0], dummysum1[0], '{} €'.format(euros[0]), horizontalalignment='center')
ax.text(titles[1], dummysum1[1], '{} €'.format(euros[1]), horizontalalignment='center')
ax.text(titles[2], dummysum1[2], '{} €'.format(euros[2]), horizontalalignment='center')
# 调整百分比标签位置到箭头右侧
ax.text(2.8, position1, label0, va='center')

ax.text(titles[0], dummysum2[0], titles[0], horizontalalignment='center')
ax.text(titles[1], dummysum2[1], titles[1], horizontalalignment='center')
ax.text(titles[2], dummysum2[2], titles[2], horizontalalignment='center')

plt.show()

内容的提问来源于stack exchange,提问作者Echo.Mike

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 22:15:49