I have a dataframe df
:
Date station_name BD_val TEMIS_val ratio longitude latitude
0 2003-01 29 295.448387 291.225806 -1.429211 158.950 - 54.500
1 2003-01 57 282.258065 279.290323 -1.051429 -26.130 -75.360
2 2003-01 57 282.258065 279.290323 -1.051429 -26.600 -75.583
3 2003-01 101 310.516129 304.677419 -1.880324 39.580 -69.010
4 2003-01 111 268.071429 274.000000 2.211564 -24.800 -89.983
... ... ... ... ... ... ... ...
153 2003-12 400 294.733333 300.000000 1.786926 11.450 -70.450
154 2003-12 454 298.176667 294.000000 -1.400736 -67.106 -68.130
155 2003-12 473 308.433333 316.000000 2.453258 -70.850 -53.140
156 2003-12 478 309.306667 304.000000 -1.715665 76.380 -69.370
Where Date
is in datetime format.
I want to create 4 plots: one each for a three month period, starting from Jan-Mar where latitude
is on the x-axis, and ratio
is on the y-axis. I want each month then to be a single line in that specific subplot.
How would I go about doing this?
So far, I have used the following method:
for key, grp in comp_df_complete.groupby(['Date']):
grp = grp.sort_values(by=['latitude'])
plt.plot(grp.latitude, grp.ratio)
plt.legend()
plt.show()
Which results in the following plot:
Which is close, with the issues being it's cluttered, plus I want each month in the 4 seasons to be visible too, in 4 faceted plots. Furthermore, the legend doesn't seem to work with this method, but that's for another question:
No artists with labels found to put in legend. Note that artists whose label start with an underscore are ignored when legend() is called with no argument.
What I finally would want is a figure similar to this one:
But with latitude
on the x-axis, ratio
on the y-axis and three lines per plot for each month in the specific season.
CodePudding user response:
Assuming that the values in Date are strings, the idea is to add a column giving the 'season' and for each, group by Date to get the lines for every month of a given season:
df['season'] = df['Date'].apply(lambda x: (int(x[-2:])-1)//3 1)
fig = plt.figure(figsize=(16, 12))
for i in range(4):
ax = fig.add_subplot(2, 2, i 1)
for key, grp in df[df['season']==i 1].groupby(['Date']):
grp = grp.sort_values(by=['latitude'])
ax.plot(grp.latitude, grp.ratio)
plt.show()