Eugene Cheung
Eugene Cheung

Reputation: 3

Formatting x-axis tickers to show only the years for a continuous time series line graph

I am able to plot the graph that I want but I would like to change the x-axis tickers to only show the years instead of showing the respective months of each year as the data range is really huge. Is there a possible way for me to do this without having to change my dataset? I am currently using matplotlib.pyplot to plot this graph.

This is the graph that I have currently with the tickers being each of the month of each year. Time Series Graph

This is a sample of the dataframe that I have now. Data Table

Hopefully someone is able to help me with this! Thank you!

Upvotes: 0

Views: 959

Answers (2)

Davide_sd
Davide_sd

Reputation: 13185

I'm going to generate some "random" data, you should insert the data from your dataframe.

# generate some data
# dates is a list of strings. For example, the first element
# will be "2005-01".
dates = []
for y in range(2005, 2013):
    dates += [str(y)+"-"+str(m) for m in range(1, 13)]
x = np.arange(len(dates))
y = np.cos(x / 4)

f, ax = plt.subplots()
ax.plot(x, y)

# xticks and labels: select only the first
# unique year
xticks, xlabels = [], []
for t, d in zip(x, dates):
    if (not xlabels) or (d[:4] != xlabels[-1]):
        xticks.append(t)
        # keep only the year
        xlabels.append(d[:4])

ax.set_xticks(xticks)
ax.set_xticklabels(xlabels)
# f.autofmt_xdate(rotation=60, ha="right")

You can remove the comment from the last line in case you would like to further customize the appearance of the dates.

enter image description here

Upvotes: 0

Bhuvan R J
Bhuvan R J

Reputation: 38

There are many ways to tackle this problem:

  1. Add another column for only months and use that column as X,PS:the actual plot won't change.
  2. use fig.autofmt__date() this tilts the dates so that the whole date will be visible.Check this documentation for further details.

Upvotes: 0

Related Questions