【发布时间】:2016-10-18 10:11:15
【问题描述】:
我有一个像这样的 df:
ID Prcp NDVI Year
1 1.4 0.1 2000
1 2.3 0.4 2001
1 4.4 0.8 2002
1 0.4 0.1 2003
2 2.1 0.6 2000
2 1.2 0.4 2001
2 3.4 0.7 2002
2 2.8 0.5 2003
我想为每个独特的ID 绘制Prcp 与NDVI 的散点图。然后,我想为绘图上的每个特定点添加 Year 的数据标签。我正在尝试这样做:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
df=pd.read_csv(r'H:\my_file.csv')
with PdfPages(r'H:\path_to_out\out.pdf') as pdf:
for i, group in df.groupby('ID'):
plot = group.plot(x=['Prcp'], y=['NDVI'], title='NDVI_' + str(i), kind='scatter').get_figure()
n=df.Year
b=df.Prcp
c=df.NDVI
for i, txt in enumerate(n):
plt.annotate(txt, (b[i],c[i]), fontsize=2.5)
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
ax = plt.gca()
ax.set_xlabel('Precipitation')
ax.set_ylabel('Mean NDVI')
pdf.savefig(plot, bbox_inches='tight', pad_inches=0)
plt.close(plot)
但这不能正常工作。
仅对 1 个绘图执行此操作,df 如下:
ID Prcp NDVI Year
1 1.4 0.1 2000
1 2.3 0.4 2001
1 4.4 0.8 2002
1 0.4 0.1 2003
我会这样做:
a=df.Prcp
b=df.NDVI
n=df.Year
with PdfPages(r'H:\graph.pdf') as pdf:
plt.title('NDVI')
plt.xlabel('Prcp')
plt.ylabel('NDVI')
plt.scatter(df.Prcp,df.NDVI, facecolors='none', s=20, edgecolors='b')
for i, txt in enumerate(n):
plt.annotate(txt, (a[i],b[i]), fontsize=2.5)
axes=plt.gca()
fig=plt.gcf()
pdf.savefig(fig)
plt.show()
编辑:
我是用这个实现的:
def label_point(Prcp,Mean, Year, ax):
a = pd.concat({'Prcp': Prcp, 'NDVI': NDVI, 'Year': Year}, axis=1)
for i, point in a.iterrows():
ax.text(point['Prcp'], point['NDVI'], str(point['Year']))
label_point(group.Prcp, group.NDVI, group.Year, ax)
【问题讨论】:
标签: python pandas matplotlib