为 Pandas DataFrame 图设置 xlim
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37469998/
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
Setting xlim for Pandas DataFrame plot
提问by mjp
I'm plotting a stacked bar plot from a Pandas DataFrame
. The index dates are in datetime
format and plot just fine. The issue I'm having is trying to set xlim
values.
我正在从Pandas DataFrame
. 索引日期的datetime
格式和绘图都很好。我遇到的问题是尝试设置xlim
值。
day_counts = {'a': count_a,
'b': count_b,
'c': count_c,
'd': count_d}
df_days = pd.DataFrame(day_counts, index=date)
The variables count_a
, .., count_d
are lists of numbers and date
is a list of datetime
objects.
变量count_a
..count_d
是数字date
列表和datetime
对象列表。
Plotting without an xlim parameter gives:
Plotting with xlim attempt 1:
使用 xlim 尝试 1 进行绘图:
ax = df_days.plot(kind='bar', stacked=True,
xlim=[pd.Timestamp('2015-09-01'), pd.Timestamp('2016-01-01')])
Plotting with xlim attempt 2:
使用 xlim 尝试 2 进行绘图:
ax = df_days.plot(kind='bar', stacked=True)
ax.set_xlim(pd.Timestamp('2015-09-01'), pd.Timestamp('2016-01-01'))
Plotting with xlim attempt 3:
使用 xlim 尝试 3 进行绘图:
ax = df_days.plot(kind='bar', stacked=True)
ax.set_xlim(datetime.datetime(2015,9,1),date[-1])
I would like to have the xlim
command inside the main plot command if possible, the dataset is really big. Suggestions?
xlim
如果可能,我希望在主绘图命令中包含该命令,数据集非常大。建议?
回答by Kyle
Per https://stackoverflow.com/a/31500017/4893407the following should work:
根据https://stackoverflow.com/a/31500017/4893407以下应该有效:
ax.set_xlim(pd.Timestamp('2015-09-01'), pd.Timestamp('2016-01-01'))
ax.set_xlim(pd.Timestamp('2015-09-01'), pd.Timestamp('2016-01-01'))
Are you sure the index of your df is a DatetimeIndex? Does it have duplicates? Is it sorted? Unsorted DatetimeIndex will cause slice indexing with Timestamps to fail.
你确定你的 df 的索引是 DatetimeIndex 吗?它有重复吗?排序了吗?Unsorted DatetimeIndex 将导致带时间戳的切片索引失败。