Matplotlib用线和图形标注条形图的方法

2024-06-24 13:38:06 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here

我想为条形图创建一个批注,将条形图的值与两个参考值进行比较。一个像图中所示的覆盖图,一种标尺,是可能的,但我愿意接受更优雅的解决方案。在

柱状图是用pandasAPI生成的matplotlib(例如data.plot(kind="bar")),因此如果解决方案能很好地处理这个问题,那就加分了。在


Tags: dataplotmatplotlibbar解决方案条形图kind柱状图
2条回答

没有直接的方法来注释条形图(据我所知),前段时间我需要注释一个,所以我写了这篇文章,也许你可以根据你的需要调整它。 enter image description here

import matplotlib.pyplot as plt
import numpy as np

ax = plt.subplot(111)
ax.set_xlim(-0.2, 3.2)
ax.grid(b=True, which='major', color='k', linestyle=':', lw=.5, zorder=1)
# x,y data
x = np.arange(4)
y = np.array([5, 12, 3, 7])
# Define upper y limit leaving space for the text above the bars.
up = max(y) * .03
ax.set_ylim(0, max(y) + 3 * up)
ax.bar(x, y, align='center', width=0.2, color='g', zorder=4)
# Add text to bars
for xi, yi, l in zip(*[x, y, list(map(str, y))]):
    ax.text(xi - len(l) * .02, yi + up, l,
            bbox=dict(facecolor='w', edgecolor='w', alpha=.5))
ax.set_xticks(x)
ax.set_xticklabels(['text1', 'text2', 'text3', 'text4'])
ax.tick_params(axis='x', which='major', labelsize=12)
plt.show()

您可以使用较小的条形图作为目标和基准指标。Pandas不能自动为条添加注释,但是您可以简单地循环这些值并使用matplotlib的pyplot.annotate。在

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

a = np.random.randint(5,15, size=5)
t = (a+np.random.normal(size=len(a))*2).round(2)
b = (a+np.random.normal(size=len(a))*2).round(2)
df = pd.DataFrame({"a":a, "t":t, "b":b})

fig, ax = plt.subplots()


df["a"].plot(kind='bar', ax=ax, legend=True)
df["b"].plot(kind='bar', position=0., width=0.1, color="lightblue",legend=True, ax=ax)
df["t"].plot(kind='bar', position=1., width=0.1, color="purple", legend=True, ax=ax)

for i, rows in df.iterrows():
    plt.annotate(rows["a"], xy=(i, rows["a"]), rotation=0, color="C0")
    plt.annotate(rows["b"], xy=(i+0.1, rows["b"]), color="lightblue", rotation=+20, ha="left")
    plt.annotate(rows["t"], xy=(i-0.1, rows["t"]), color="purple", rotation=-20, ha="right")

ax.set_xlim(-1,len(df))
plt.show()

enter image description here

相关问题 更多 >