简体   繁体   English

在条形图上方 3/4 处显示条形图的值

[英]Display values of a bar graph 3/4 of the way up the bar

I have a plot with a bar and line graph on different y axes.我有一个 plot 在不同的 y 轴上带有条形图和折线图。 I need to label the bar graph with it's corresponding values 3/4 of the way up the height of the bar, and label the line graph with its values just above each point on the line.我需要 label 条形图,它的相应值是条形高度的 3/4,而 label 线形图的值正好在线上每个点的上方。 How do I do this?我该怎么做呢?

My code and graph is as follows:我的代码和图表如下:

import matplotlib.pyplot as plt
import pandas as pd

width=.7

t=pd.DataFrame({'bars':[3.4,3.1,5.1,5.1,3.8,4.2,5.2,4.0,3.6],'lines':[2.4,2.2,2.4,2.1,2.0,2.1,1.9,1.8,1.9]})
ax1 = t['bars'].plot(kind='bar',width=width,color='lightgrey')
ax2 = t['lines'].plot(secondary_y=True, color='red')
ax1.plot(label='bars')
ax2.plot(label='lines')
lines,labels=ax1.get_legend_handles_labels()
lines2,labels2=ax2.get_legend_handles_labels()
ax2.legend(lines+lines2,labels+labels2)

ax1.yaxis.grid(linestyle='dashed')
ax1.set_axisbelow(True)
ax1.set_xticklabels(('1','2','3','4','5','6','7','8','9'))
ax1.set_ylim(0,6)
ax1.set_ylabel('title1')
ax2.set_ylim(0, 2.5)
ax2.set_ylabel('title2')

plt.show()

图片

After plotting the bars, annotate it with the information:绘制条形图后,使用以下信息对其进行注释:

# other codes
ax1 = t['bars'].plot(kind='bar',width=width,color='lightgrey')

for p in ax1.patches:
    w,h = p.get_width(), p.get_height()
    x = p.get_x()
    ax1.text(x + w/2, h * .75,     # your 3/4 here
             f'{h}', va='center', ha='center')

# other codes

Output: Output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM