0

I have some data from a csv file and that data is a dictionary whose values are numpy arrays. Here is some part of my data:

{'Date': array(['2015-01-01', '2015-01-02', '2015-01-03', ..., '2017-12-29',
   '2017-12-30', '2017-12-31'], dtype='<U11'), 'Year': array([2015, 2015, 2015, ..., 2017, 2017, 2017]), 'Month': array([ 1,  1,  1, ..., 12, 12, 12]), 'Day': array([ 1,  2,  3, ..., 29, 30, 31]), 'Consumption': array([1111.336 , 1300.884 , 1265.271 , ..., 1295.0875, 1215.449 ,
   1107.1149]), 'Wind': array([325.128, 603.558, 462.953, ..., 584.277, 721.247, 721.176]), 'Solar': array([17.079,  7.758,  7.236, ..., 29.854,  7.467, 19.98 ])}

Then, according to that data, I plotted a graph whose x values are dates and y values are consumption, wind and solar information from the data. Let me show you my graph and code:

plt.plot(data['Date'], data['Consumption'], label= 'Consumption')
plt.plot(data['Date'] , data['Wind'], label= 'Wind')
plt.plot(data['Date'] , data['Solar'], label='Solar')
plt.legend()

My Graph

Here is my problem. I need to use xticks function to put the month and year information onto the x axis. For example, when my y values show the information of '2015-01-01' date, I need to put 'Jan15' string onto the x axis. I need to do that for all first days of months like 'Feb15' ..... 'Dec17'. The result should be like that:

Result Graph

Can someone help me about that?

captaingb
  • 13
  • 4
  • Lots of examples on SO. You have to set the Locator (seemingly every 30 days) and use the DateFormatter. Because I am too lazy to find an exact duplicate, I will link to an [answer of mine with further links](https://stackoverflow.com/a/65343940/8881141) – Mr. T Jan 13 '21 at 09:50
  • I recommend converting them to `datetime` than `matplotlib` distributes them automatically on the axis and you can specify the format with `ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('mmm%dd'))`, see [this post](https://stackoverflow.com/questions/23219218/formatting-x-axis-with-dates-format-matplotlib#23223250) – max Jan 14 '21 at 06:39

1 Answers1

0

Update
Without any other modules, you can simply use a dict or list to convert month written in numbers into letters. Use str.split to separate month and date.
An example:

a = '2015-01-01'
split_a = a.split('-')
# split_a will be: ["2015", "01", "01"]

My approach would be using the module datetime (doc here).

  1. Create a list to hold the strings for xtick.
  2. Use strptime() to convert str into a datetime object, then use strftime() to convert datetime object into a str with the format you want.
  3. Use plt.xticks([where to draw the ticks], [what shows up in the plot])
Frank
  • 26
  • 1
  • 3