如何在绘图上标注/显示y值

时间:2018-10-26 18:38:13

标签: python pandas matplotlib

如何在matlotlib图上显示数据(y轴值)? 我找到了与此相关的post,我尝试了建议的解决方案,但此方法在这里不起作用,至少我无法弄清楚。如果您能提供帮助,我将不胜感激。谢谢。

我在这里试图在三个不同的图中绘制相对于时间的y值(平均值,平均值,距离)。

这是我的代码:

import matplotlib.pyplot  as plt
import numpy as np
import pandas as pd
import mysql.connector
from matplotlib import style
from matplotlib.pyplot import figure
from matplotlib import pyplot

conn = mysql.connector.MySQLConnection(user='root', password='', host='127.0.0.1', database='DB')
cursor = conn.cursor()
sql = "SELECT Time, mean, Aver, Dist FROM datatb order by Time Desc limit 100"
cursor.execute(sql)
result = cursor.fetchall()

df = pd.DataFrame(list(result),columns=["Time","Mean","Aver","Dist"])


plt.figure(num=None, figsize=(15, 12), dpi=150, facecolor='w', edgecolor='k')

plt.subplot(2,1,1)
plt.title('Mean')
plt.plot(df['Time'], df["Mean"],'o-', c='blue',label=r'$Mean$')
plt.legend(loc='best')
ax = plt.gca()
ax.invert_xaxis()

plt.figure(num=None, figsize=(15, 12), dpi=150, facecolor='w', edgecolor='k')
plt.subplot(2,1,2)
plt.title('Aver')
plt.plot(df['Time'], df["Aver"],'o-', c='green', label=r'$Aver$')
plt.legend(loc='best')
ax = plt.gca()
ax.invert_xaxis()

plt.figure(num=None, figsize=(15, 12), dpi=150, facecolor='w', edgecolor='k')
plt.subplot(2,1,2)
plt.title('Dist')
plt.plot(df['Time'], df["Dist"], 'o-', c='brown', label=r'$Dist$')
plt.legend(loc='best')
ax = plt.gca()
ax.invert_xaxis()


conn.close()
cursor.close()

我的情节看起来像这样:

enter image description here

1 个答案:

答案 0 :(得分:2)

使用annotate


示例:

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

现在,只需将xy替换为df['Time']df["Mean"]

enter image description here