【问题标题】:Label a line graph above each point on the line with its value python用它的值python标记线上每个点上方的折线图
【发布时间】:2021-11-30 18:26:52
【问题描述】:

我有一个在不同 y 轴上带有条形图和折线图的图。我需要用它的值标记折线图,就在直线上的每个点上方。我已经尝试过这样的事情

for p in ax2.patches:
    w,h = p.get_width(), p.get_height()
    x = p.get_x()
    ax2.text(x + w/2, h * 1.1, 
             f'{h}', va='center', ha='center')

这是我用来标记条形图的结构。我还尝试了此页面上列出的示例https://queirozf.com/entries/add-labels-and-text-to-matplotlib-plots-annotation-examples,但无法弄清楚,因为这些示例只是使用两个系列来生成情节。

我的代码和图表如下:

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

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    试试:

    for x,y in t["lines"].items():
        plt.annotate(f"{y:.1f}", (x,y), textcoords="offset points", xytext=(0, 5), ha="center")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      相关资源
      最近更新 更多