简体   繁体   中英

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!

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.

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.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM