为 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:17:54  来源:igfitidea点击:

Setting xlim for Pandas DataFrame plot

pythonpandas

提问by mjp

I'm plotting a stacked bar plot from a Pandas DataFrame. The index dates are in datetimeformat and plot just fine. The issue I'm having is trying to set xlimvalues.

我正在从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_dare lists of numbers and dateis a list of datetimeobjects.

变量count_a..count_d是数字date列表和datetime对象列表。

Plotting without an xlim parameter gives: enter image description here

没有 xlim 参数的绘图给出: 在此处输入图片说明

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 xlimcommand 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 将导致带时间戳的切片索引失败。