简体   繁体   English

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

[英]pandas .plot() x-axis tick frequency -- how can I show more ticks?

I am plotting time series using pandas.plot() and want to see every month shown as an x-tick.我正在使用 pandas.plot() 绘制时间序列,并希望看到每个月都显示为 x-tick。

Here is the dataset structure这是数据集结构数据集

Here is the result of the.plot()这是 the.plot() 的结果

在此处输入图像描述

I was trying to use examples from other posts and matplotlib documentation and do something like我试图使用其他帖子和 matplotlib 文档中的示例并执行类似的操作

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.我也尝试通过xticks = df.index ,但它没有改变任何东西。

What would be the rigth way to show more ticks on x-axis?在 x 轴上显示更多刻度的正确方法是什么?

No need to pass any args to MonthLocator . 无需将任何args传递给MonthLocator Make sure to use x_compat in the df.plot() call per @Rotkiv's answer. 确保在每个@Rotkiv的答案的df.plot()调用中使用x_compat

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()

You could also format the x-axis ticks and labels of a pandas DateTimeIndex "manually" using the attributes of a pandas Timestamp object. 您还可以使用pandas Timestamp对象的属性“手动”格式化pandas DateTimeIndex的x轴刻度和标签。

I found that much easier than using locators from matplotlib.dates which work on other datetime formats than pandas (if I am not mistaken) and thus sometimes show an odd behaviour if dates are not converted accordingly. 我发现使用matplotlib.dates中的定位器比使用其他日期时间格式而不是pandas(如果我没有记错的话)更容易,因此如果没有相应地转换日期,有时会显示奇怪的行为。

Here's a generic example that shows the first day of each month as a label based on attributes of pandas Timestamp objects: 这是一个通用示例,它将每个月的第一天显示为基于pandas Timestamp对象属性的标签:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


# data
dim = 8760
idx = pd.date_range('1/1/2000 00:00:00', freq='h', periods=dim)
df = pd.DataFrame(np.random.randn(dim, 2), index=idx)

# select tick positions based on timestamp attribute logic. see:
# https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Timestamp.html
positions = [p for p in df.index
             if p.hour == 0
             and p.is_month_start
             and p.month in range(1, 13, 1)]
# for date formatting, see:
# https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
labels = [l.strftime('%m-%d') for l in positions]

# plot with adjusted labels
ax = df.plot(kind='line', grid=True)
ax.set_xlabel('Time (h)')
ax.set_ylabel('Foo (Bar)')
ax.set_xticks(positions)
ax.set_xticklabels(labels)

plt.show()

yields: 收益率:

在此输入图像描述

Hope this helps! 希望这可以帮助!

这里描述的正确方法使用x_compat参数,可以抑制自动刻度分辨率调整

df.A.plot(x_compat=True)

If you want to just show more ticks, you can also dive deep into the structure of pd.plotting._converter : 如果您只想显示更多刻度,您还可以深入了解pd.plotting._converter的结构:

dai = ax.xaxis.minor.formatter.plot_obj.date_axis_info
dai['fmt'][dai['fmt'] == b''] = b'%b'

After plotting, the formatter is a TimeSeries_DateFormatter and _set_default_format has been called, so self.plot_obj.date_axis_info is not None . 密谋后, formatterTimeSeries_DateFormatter_set_default_format被调用,所以self.plot_obj.date_axis_info is not None You can now manipulate the structured array .date_axis_info to be to your liking, namely contain less b'' and more b'%b' 您现在可以根据自己的喜好操纵结构化数组.date_axis_info ,即包含较少的b''和更多b'%b'

Remove tick labels:删除刻度标签:

ax = df.plot(x='date', y=['count'])
every_nth = 10
for n, label in enumerate(ax.xaxis.get_ticklabels()):
  if n % every_nth != 0:
    label.set_visible(False)

Lower every_nth to include more labels, raise to keep fewer.降低every_nth以包含更多标签,提高以保留更少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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