python - Pandas 在 x 轴上绘制 : Separate color for weekends, pretty-print 时间

标签 python matplotlib pandas time-series

我创建了一个看起来像 enter image description here 的图

我有几个问题:

  1. 我怎样才能具体显示周末。我曾想过的一些方法是获取与周末相对应的索引,然后在 xlims 之间绘制透明条。也可以绘制矩形。如果能在 Pandas 中简单明了就更好了。
  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)])

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);

产生的输出如下: enter image description here

了解 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)

最佳答案

我尝试了很多,现在这些 hack 起作用了。等待更多 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)

此外,在绘图时我做了以下更改

ax=df.plot(kind='bar',rot=0)

这使得标签处于 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

现在,该图看起来更有用并且涵盖了这些用例。 enter image description here

关于python - Pandas 在 x 轴上绘制 : Separate color for weekends, pretty-print 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16480232/

相关文章:

python - 如何在每次出现时保留 numpy 数组的最新元素

python - 如何使用seaborn和ipywidgets制作交互式条形图

python - 使用 .loc 和 OR 运算符返回 ValueError

python - matplotlib 中的文本对象无法正确响应缩放

python - xarray - 按特定日期范围对数据进行分组

python - 使用 pandas 将函数应用于每行的每个列值

python - 通过 .loc 在 Panda 切片上进行矩阵运算的有效方法

python - 如何在python中绘制 'historical'数据

python - 尝试在 Fedora 21 上安装 PythonMagic 0.9.11 时出错

python - 在Python中绘制3D曲面