简体   繁体   中英

How to format the x-axis to show every year on the major ticks

I have tried removing every set_xticks, or grids options and just plotting the data frame and I cannot get the X-axis to stop skipping years.

日期跳过问题

The index is DateTime stamps YYYY-MM-DD, and the columns are all floats.

DF结构

ax = Export_DF.plot.area()

ax.grid(color='black',alpha=.3)
ax.grid(which='minor', linestyle=':', linewidth='0.5', color='black')

major_ticks = np.arange(0, 101, 20)
minor_ticks = np.arange(0, 101, 5)

ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)

X_Dates = []
for i in range(12):
    X_Dates.append(pd.to_datetime('1/1/'+str(2010+i)))
ax.xticks(X_Dates)
ax.set_xticks(X_Dates,minor=True)

ax.grid(which='minor', alpha=0.3)
ax.grid(which='major', alpha=0.5)

handles, labels = ax.get_legend_handles_labels()
ax.legend(reversed(handles), reversed(labels),bbox_to_anchor=(1.02, 1))  # reverse both handles and labels

for i in range(len(Export_DF)):
    temp_series = Export_DF.iloc[i]
    temp_x_cord = temp_series.name
    count = [0]
    for j in temp_series:
        if j != 0:
            count.append(count[-1]+j)
            ax.annotate(str(round(j,1)),(temp_x_cord,(count[-1]+count[-2])/2),size=8,ha='center')

plt.show()
  • When working with datetime data on the axis, matplotlib.dates should be used.
  • Using the implementation shown for Date tick labels
  • datemin and datemax must be in a datetime format to be recognized by the DateFormatter . As such, use np.datetime64(data.index.array[0], 'Y') , which results in numpy.datetime64('2021') , where as data.index.year.min() results in an int .
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import pandas as pd

# create a sample dataframe
data = pd.DataFrame({'v1': [10]*4000, 'v2': [20]*4000}, index=pd.bdate_range('2021-01-11', freq='D', periods=4000))

years = mdates.YearLocator()   # every year
years_fmt = mdates.DateFormatter('%Y')

# create the plot
ax = data.plot.area(x='date', figsize=(8, 6))

# format the ticks only for years on the major ticks
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)

# round to nearest years. Also, the index must be sorted and in a datetime format.
datemin = np.datetime64(data.index.array[0], 'Y')
datemax = np.datetime64(data.index.array[-1], 'Y') + np.timedelta64(1, 'Y')

# set the x-axis limits
ax.set_xlim(datemin, datemax)

# turn the grid on, if desired
ax.grid(True)

plt.show()

Formatted Plot

在此处输入图像描述

Unformatted Plot

ax = data.plot.area(figsize=(8, 6))

在此处输入图像描述

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