Pandas Plots:周末分开的颜色,x轴上的漂亮印刷时间

Nip*_*tra 9 python time-series matplotlib pandas

我创建了一个看起来像的情节在此输入图像描述

我有几个问题:

  1. 我怎么能专门展示周末.我想到的一些方法是抓住对应周末的指数,然后在xlims之间绘制透明条.也可以绘制矩形.如果可以在熊猫中明白地完成它将是最好的.
  2. 日期格式不是最漂亮的

以下是用于生成此图的代码

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)])
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

产生的产出如下: 在此输入图像描述

了解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)
Run Code Online (Sandbox Code Playgroud)

Nip*_*tra 11

我尝试了很多,现在这些黑客工作.等待更多Pythonic和一致的解决方案.解决标签问题:

def correct_labels(ax):
    labels = [item.get_text() for item in ax.get_xticklabels()]
    days=[label.split(" ")[0] for label in labels]
    months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
    final_labels=[]
    for i in range(len(days)):
        a=days[i].split("-")
        final_labels.append(a[2]+"\n"+months[int(a[1])-1])
    ax.set_xticklabels(final_labels)
Run Code Online (Sandbox Code Playgroud)

同时在绘图时我做了以下更改

ax=df.plot(kind='bar',rot=0)
Run Code Online (Sandbox Code Playgroud)

这使标签处于0旋转状态.

为了找到周末并突出显示它们,我写了以下两个函数:

def find_weekend_indices(datetime_array):
    indices=[]
    for i in range(len(datetime_array)):
        if datetime_array[i].weekday()>=5:
            indices.append(i)
    return indices

def highlight_weekend(weekend_indices,ax):
    i=0
    while i<len(weekend_indices):
         ax.axvspan(weekend_indices[i], weekend_indices[i]+2, facecolor='green', edgecolor='none', alpha=.2)
         i+=2
Run Code Online (Sandbox Code Playgroud)

现在,该图看起来更有用,并涵盖了这些用例.在此输入图像描述


Bra*_*des 5

既然Pandas .dt在每个系列中都支持功能强大的名称空间,则可以在没有任何显式Python循环的情况下确定每个周末的开始和结束。只需过滤您的时间值t.dt.dayofweek >= 5以仅选择周末的时间,然后按每周不同的虚假值进行分组-我在这里使用它是year * 100 + weekofyear因为结果看起来像201603调试时读取的结果相当令人愉快。

结果函数为:

def highlight_weekends(ax, timeseries):
    d = timeseries.dt
    ranges = timeseries[d.dayofweek >= 5].groupby(d.year * 100 + d.weekofyear).agg(['min', 'max'])
    for i, tmin, tmax in ranges.itertuples():
        ax.axvspan(tmin, tmax, facecolor='orange', edgecolor='none', alpha=0.1)
Run Code Online (Sandbox Code Playgroud)

只需将轴和时间轴作为轴传递,它将为您x突出显示周末!