2017-05-18 32 views
0

enter image description hereMatplotlib方式来注释栏地块用线条和数字

我想创建注释于所述杆的值进行比较以两个参考值的条形图。图片中显示的叠加层是一种职员标尺,但我愿意接受更优雅的解决方案。

使用pandas API生成条形图至matplotlib(例如data.plot(kind="bar")),因此如果解决方案与其配合良好,则会产生加值。

回答

1

您可以使用目标和基准指标小酒吧。熊猫不能自动注释条形码,但是您可以简单地遍历这些值并使用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

1

没有直接的方法来标注条形图(据我所知)前段时间我需要注释一个,所以我写了这个,也许你可以根据自己的需要进行调整。 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()