Matplotlib用线条和图形注释条形图的方法 [英] Matplotlib way to annotate bar plots with lines and figures

查看:345
本文介绍了Matplotlib用线条和图形注释条形图的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为条形图创建一个注释,将条形图的值与两个参考值进行比较.可以使用图片中所示的覆盖层(一种人员规),但是我愿意接受更优雅的解决方案.

I would like to create an annotation to a bar chart that compares the value of the bar to two reference values. An overlay such as shown in the picture, a kind of staff gauge, is possible, but I'm open to more elegant solutions.

条形图是使用pandasmatplotlib的API生成的(例如data.plot(kind="bar")),因此,如果解决方案与此配合得当,则加号.

The bar chart is generated with the pandas API to matplotlib (e.g. data.plot(kind="bar")), so a plus would be if the solution is playing nicely with that.

推荐答案

您可以使用较小的条形作为目标指标和基准指标.熊猫无法自动注释条形,但是您可以简单地遍历值并使用matplotlib的pyplot.annotate代替.

You may use smaller bars for the target and benchmark indicators. Pandas cannot annotate bars automatically, but you can simply loop over the values and use matplotlib's pyplot.annotate instead.

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()

这篇关于Matplotlib用线条和图形注释条形图的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆