I have a df like so:
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
and I want to do a scatter plot of Prcp vs. NDVI for each unique ID. I then want to add a data label for Year for each particular point on the plot. I am trying to do it like this:
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_outout.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)
but this doesn't work correctly.
To do this for just 1 plot, with a df like this:
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
I would do it like this:
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()
Aucun commentaire:
Enregistrer un commentaire