简体   繁体   English

Label 线上每个点上方的折线图及其值 python

[英]Label a line graph above each point on the line with its value python

I have a plot with a bar and line graph on different y axes.我有一个 plot 在不同的 y 轴上带有条形图和折线图。 I need to label the line graph with its values just above each point on the line.我需要 label 折线图,其值正好在线上的每个点上方。 I've tried something like this我试过这样的东西

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

which is a structure I used to label the bar graph.这是我用来label结构的条形图。 I also tried the example listed on this page https://queirozf.com/entries/add-labels-and-text-to-matplotlib-plots-annotation-examples , but couldn't figure it out since the examples are just using two series to generate the plot.我还尝试了此页面上列出的示例https://queirozf.com/entries/add-labels-and-text-to-matplotlib-plots-annotation-examples ,但由于示例只是使用而无法弄清楚两个系列生成 plot。

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

图片

Try:尝试:

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

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

相关问题 python图形上的线未按时间顺序连接每个点 - Line on a python graph doesn't connect each point chronologically Python中直线(数字线)上的图形点 - Graph point on straight line (number line) in Python Python 在特定行上方搜索包含某个字符串的行并更新其值 - Python search a line containing some string above a particular line and update its value 在Python中将文本文件的每个值移至其各自的行 - Moving each value of a text file to its own line in Python Python Dash 图线标签截止 - Python Dash graph line label cutoff 在python中将行置于搜索值之上 - Getting the line above a search value in python 每次变量更改时在新行上启动标签? (Python Tkinter模块) - starting a label on a new line each time its variable changes? (Python Tkinter module) Python 对数函数并选择该日志线上方的点 - Python logarithm function and select point above that log line 使用 OpenCV 在 python 中获取横向图像上每行文本的上方和下方的行或图像中文本上方的框 - get a lines above and below each line of text on a landscape image or boxes over text in an image without losing its resolution in python using OpenCV 如何在matplotlib的折线图中绘制最大值点? - How do I plot the point of max value on a line graph in matplotlib?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM