python - 如何格式化 x 轴以显示每年的主要刻度
问题描述
我尝试删除每个 set_xticks 或网格选项并仅绘制数据框,但我无法让 X 轴停止跳过年份。
索引是日期时间戳 YYYY-MM-DD,列都是浮点数。
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()
解决方案
- 在轴上处理日期时间数据时,
matplotlib.dates
应使用。 - 使用日期刻度标签所示的实现
datemin
并且datemax
必须采用日期时间格式才能被DateFormatter
. 因此,使用np.datetime64(data.index.array[0], 'Y')
, 导致numpy.datetime64('2021')
, where asdata.index.year.min()
导致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()
格式化绘图
未格式化的绘图
ax = data.plot.area(figsize=(8, 6))
推荐阅读
- matlab - 如何在没有数据剪辑的情况下保存音频 wav 文件?
- java - 有没有办法知道特定程序运行的最大达到 JVM 调用堆栈深度?
- java - 为什么它打印这个而不是那个?
- javascript - 使用基线标准来验证对象?
- arrays - 批量迭代另一个 for 循环中的数组
- java - 使用 cancel() 后通知关闭并重新打开;
- java - 什么是 generic 的现实生活示例?
- ms-access - 访问运行时错误 2475 *偶尔*发生
- apache-storm - Storm 未从 HDFS 读取数据(HdfsSpout 无法识别)
- sapui5 - sapui5 如何在控制器中读取 PDF 文件内容