【发布时间】:2013-05-05 00:26:31
【问题描述】:
我创建了一个看起来像的情节
我有几个问题:
- 我怎样才能特别显示周末。我曾想过的一些方法是获取与周末相对应的索引,然后在 xlims 之间绘制透明条。也可以绘制相同的矩形。最好能在 Pandas 中简单地完成。
- 日期格式不是最漂亮的
以下是用于生成此图的代码
ax4=df4.plot(kind='bar',stacked=True,title='Mains 1 Breakdown');
ax4.set_ylabel('Power (W)');
idx_weekend=df4.index[df4.index.dayofweek>=5]
ax.bar(idx_weekend.to_datetime(),[1800 for x in range(10)])
ax.bar 专门用于突出显示周末,但它不会产生任何可见的输出。 (问题 1)
对于问题 2,我尝试使用 Major Formatter 和 Locators,代码如下:
ax4=df4.plot(kind='bar',stacked=True,title='Mains 1 Breakdown');
ax4.set_ylabel('Power (W)');
formatter=matplotlib.dates.DateFormatter('%d-%b');
locator=matplotlib.dates.DayLocator(interval=1);
ax4.xaxis.set_major_formatter(formatter);
ax4.xaxis.set_major_locator(locator);
产生的输出如下:
了解 Dataframe 的样子可能会有所帮助
In [122]:df4
Out[122]:
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 36 entries, 2011-04-19 00:00:00 to 2011-05-24 00:00:00
Data columns:
(0 to 6 AM) Dawn 19 non-null values
(12 to 6 PM) Dusk 19 non-null values
(6 to 12 Noon) Morning 19 non-null values
(6PM to 12 Noon) Night 20 non-null values
dtypes: float64(4)
【问题讨论】:
-
在 matplotlib 中实现这一点并不是很复杂,例如用另一种颜色标记周末的刻度标签是一种公认的解决方案。要归档周末,请使用 matplotlibs
WeekdayLocator。就我个人而言,我认为如果在 matplotlib 而不是 pandas 中绘制绘图,自定义绘图会更容易。 -
@nordev:也将此添加到下面的解决方案中,该解决方案现在位于社区 wiki 中
标签: python matplotlib pandas time-series