在matplotlib

时间:2016-03-13 15:53:57

标签: python matplotlib annotations

我想用示例图表中的文本注释图表的轴。具体来说,我想用不同的标题注释轴的区域(XYZ,ABC,MNO等以红色显示)。

我使用此示例(绘制条形图)生成了图表:http://matplotlib.org/examples/api/barchart_demo.html

有人可以帮我画这样的线以及沿轴添加文字吗?任何指向示例的指针也是值得赞赏的。我不知道除了用图片描述之外,还有什么方法可以表达我想做的事情。

Example figure showing the text annotation along X and Y axes (shown using XYZ, MNO, etc.) in red

1 个答案:

答案 0 :(得分:3)

快速阅读文档会有所帮助,可以在http://matplotlib.org/users/annotations_intro.html找到。我使用了文档

中描述的annotate函数

这是一段代码,可以完成x轴所需的操作。此代码的大部分内容取自您在问题中提供链接的示例。

N = 5
menMeans = (20, 35, 30, 35, 27)
menStd = (2, 3, 4, 1, 2)
ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd)
womenMeans = (25, 32, 34, 20, 25)
womenStd = (3, 5, 2, 3, 3)
rects2 = ax.bar(ind + width, womenMeans, width, color='y', yerr=womenStd)

# add some text for labels, title and axes ticks
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind + width)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.legend((rects1[0], rects2[0]), ('Men', 'Women'))

######### annotating the x axis   #########
ax.annotate('', xy=(0, -2),xytext=(3,-2.09),                     #draws an arrow from one set of coordinates to the other
            arrowprops=dict(arrowstyle='<->',facecolor='red'),   #sets style of arrow and colour
            annotation_clip=False)                               #This enables the arrow to be outside of the plot

ax.annotate('xyz',xy=(1.1,-3.8),xytext=(1.3,-3.8),               #Adds another annotation for the text that you want
            annotation_clip=False)


ax.annotate('', xy=(3.1, -2),xytext=(5,-2.09),                   #Repeating for however many arrows you want under the axes
            arrowprops=dict(arrowstyle='<->',facecolor='red'),
            annotation_clip=False)

ax.annotate('abc',xy=(3.6,-3.8),xytext=(3.9,-3.8),
            annotation_clip=False)

######## Can add further annotations for the y-axis here similar to the above ########



# by changing the coorinates of the above you can repeat this for the y axis too
def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                '%d' % int(height),
                ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
plt.show()

这给出了下图:

enter image description here

您需要重现此操作才能对y轴执行相同的操作