pandas .plot() x 轴刻度频率——如何显示更多刻度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39714724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pandas .plot() x-axis tick frequency -- how can I show more ticks?
提问by Rotkiv
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 result of the .plot()
这是 .plot() 的结果
I was trying to use examples from other posts and matplotlib documentationand 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 轴上显示更多刻度的正确方法是什么?
采纳答案by Kyle
No need to pass any args to MonthLocator
. Make sure to use x_compat
in the df.plot()
call per @Rotkiv's answer.
无需将任何参数传递给MonthLocator
. 确保根据@Rotkiv 的回答x_compat
在df.plot()
通话中使用。
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()
回答by Cord Kaldemeyer
You could also format the x-axis ticks and labels of a pandas DateTimeIndex
"manually" using the attributes of a pandas Timestamp
object.
您还可以DateTimeIndex
使用熊猫Timestamp
对象的属性“手动”格式化熊猫的 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:
这是一个通用示例,它根据 pandasTimestamp
对象的属性将每个月的第一天显示为标签:
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!
希望这可以帮助!
回答by Rotkiv
回答by flying sheep
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
. You can now manipulate the structured array .date_axis_info
to be to your liking, namely contain less b''
and more b'%b'
密谋后,formatter
是TimeSeries_DateFormatter
和_set_default_format
被调用,所以self.plot_obj.date_axis_info is not None
。现在,您可以操纵结构阵列.date_axis_info
是根据自己的喜好,即含有较少的b''
多b'%b'