用户登录
用户注册

分享至

pandas .p??lot() x 轴刻度频率——如何显示更多刻度?

  • 作者: LOVE语诺
  • 来源: 51数据库
  • 2022-11-15

问题描述

我正在使用 pandas .p??lot() 绘制时间序列,并希望看到每个月都显示为 x-tick.

这是数据集结构

这是 .plot() 的结果

我试图使用其他帖子和 matplotlib

  • 未格式化的 x 轴

I am plotting time series using pandas .plot() and want to see every month shown as an x-tick.

Here is the dataset structure

Here is the result of the .plot()

I was trying to use examples from other posts and matplotlib documentation and do something like

ax.xaxis.set_major_locator(
   dates.MonthLocator(revenue_pivot.index, bymonthday=1,interval=1))

But that removed all the ticks :(

I also tried to pass xticks = df.index, but it has not changed anything.

What would be the rigth way to show more ticks on x-axis?

解决方案

No need to pass any args to MonthLocator. Make sure to use x_compat in the df.plot() call per @Rotkiv's answer.

import pandas as pd
import numpy as np
import matplotlib.pylab as plt
import matplotlib.dates as mdates

df = pd.DataFrame(np.random.rand(100,2), index=pd.date_range('1-1-2018', periods=100))
ax = df.plot(x_compat=True)
ax.xaxis.set_major_locator(mdates.MonthLocator())
plt.show()

  • formatted x-axis with set_major_locator

  • unformatted x-axis

软件
前端设计
程序设计
Java相关