Home > other >  drawing bars for time series with years as bins in matplotlib
drawing bars for time series with years as bins in matplotlib

Time:03-14

so i have data as readings recorded as monthly averages over time. I have already drawn it but the problem is the graph is kinda messed up and the X axis is unreadable, i have been trying for two days to draw it without a success, any help would be appreciated. i was able to get the image i want from plotly using the exact same code just instead drawing using "iplot" instead of "plot", you can see the result in the second image. but the problem is that i have no way of exporting it as SVG, besides i really like matplotlib so i want to use it. the code is at the end, i should also note that all the commented out lines are failed attempts.

here is the graph that i get: This is the image i get

and this is the image i want: This is the kind of image i want

lastly here is the code:

fig, ax= plt.subplots(1,1)
# ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
ax=hist.count().plot(kind='bar',  color='brown',  legend=True)
# ax.xaxis.set_major_locator(matplotlib.dates.YearLocator(10))
# ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("\n%Y"))
# plt.setp(ax.get_xticklabels(), rotation=0, ha="center")
# ax.xaxis.set_major_formatter(DateFormatter("%Y"))
# fig.autofmt_xdate()
# plt.xticks(hist['Date'], rotation=90)
plt.show()

This is the previous state of the data (grouped by WellCode): enter image description here

To solve this problem, you should convert your date column from str to datetime and see how the plot looks like:

df = pd.DataFrame(lst, columns=['Date'])

df["Date"] =pd.to_datetime(df["Date"])  # add this line before plotting

plt.hist(df["Date"]) 
plt.show()

enter image description here

If you want to save your histogram plot in .svg format, you should add this line directly after the plot in this way:

plt.hist(df["Date"]) 
plt.savefig("test.svg")   # add your line directly after plot.hist()
plt.show()

Final remark: now you can use the additional settings smoothly to set up the x-axis as you prefer, this is an example:

ax.xaxis.set_major_locator(mdates.YearLocator(2)) # show every 2 years on the x-axis 
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b'))

enter image description here

  • Related