-1

currently i have this code:

def graph_s(self):
    ex_list = list()
    time = list()
    if(len(self.sheet) > 1):
        for index, row in self.sheet.iterrows():
            ts = date(int(row['Year']), int(row['Month']), 1)
            time.append(ts)
            ex_list.append(float(row['grocery']) + float(row['transportation']) + float(row['leisure']) + float(row['utilities']) + float(row['savings']) + float(row['bills']))
        z = sorted(zip(time,ex_list))
        x=[date(2021,i,1) for i in z]
        y=[i[1] for i in z]
        plt.plot(x, y)
        plt.show()
        main()
    else:
        print('Sorry! There is not enough information to create a graph of you spending over time.')
        main()

but the graph isnt what i wanted. i want to change the x-axis to a nicer version e.g. 2021-10, i want to omit the day

enter image description here enter image description here

mosc9575
  • 5,618
  • 2
  • 9
  • 32
user21
  • 1
  • 1
    Do you use matplotlib for plotting? If so, please add this as a tag to find some matplotlib experts. – mosc9575 Oct 08 '21 at 07:55
  • 1
    Does this answer your question? [Editing the date formatting of x-axis tick labels in matplotlib](https://stackoverflow.com/questions/14946371/editing-the-date-formatting-of-x-axis-tick-labels-in-matplotlib) – mosc9575 Oct 08 '21 at 07:57
  • You can rotate tick labels: `plt.xticks(rotation=90)` – Michael Oct 08 '21 at 08:14

1 Answers1

0

You have to define a DateFormatter for your x-axis. In your case you want only years and months. This is the notation: '%Y-%m' and below you can see how to apply the formatter.

myFmt = mdates.DateFormatter('%Y-%m')
ax1.xaxis.set_major_formatter(myFmt)

Example This is adapted from here:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cbook as cbook
# Fixing random state for reproducibility
np.random.seed(19680801)

# load up some sample financial data
r = (cbook.get_sample_data('goog.npz', np_load=True)['price_data']
     .view(np.recarray))
# create two subplots with the shared x and y axes

fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
ax1.plot(r.date, r.close, lw=2)
myFmt = mdates.DateFormatter('%Y-%m')
plt.xticks(rotation=45)
ax1.xaxis.set_major_formatter(myFmt)

date formatter

mosc9575
  • 5,618
  • 2
  • 9
  • 32