简体   繁体   English

将格式应用于Jupyter Notebook中的所有子图

[英]Apply formatting to all subplots in Jupyter notebook

When plotting 3 pandas dataframe with different time resolution (hourly, daily, monthly) in Jupyter Notebook, I would like to apply a consistent format to all three subplots showing only month and not year (ie Jan, Feb, Mar, and not Jan 2010, Feb 2010, Mar 2010). 在Jupyter Notebook中绘制具有不同时间分辨率(每小时,每天,每月)的3个熊猫数据框时,我想对所有三个子图应用一致的格式,使其仅显示月份而不显示年份(即2010年1月,2月,3月而不是2010年1月) ,2010年2月,2010年3月)。

Question: how to apply the formatting across all subplots? 问题:如何在所有子图中应用格式?

Import libraries 导入库

import matplotlib
import matplotlib.dates
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import seaborn as sns
%matplotlib inline

Create 3 dataframes 创建3个数据框

hourly = pd.DataFrame({'val': np.random.rand(24*365)}, index=pd.date_range('2010-01-01', '2010-12-31 23:00', freq='1H'))
daily = pd.DataFrame({'val': np.random.rand(365)}, index=pd.date_range('2010-01-01', '2010-12-31 23:00', freq='1D'))
monthly = pd.DataFrame({'val': np.random.rand(12)}, index=pd.date_range('2010-01-01', '2010-12-31 23:00', freq='1M'))

Plot and apply formatting to three subplots 绘制格式并将其应用于三个子图

def plot2(hourly, daily, monthly):
    f, ax = plt.subplots(3, 1, sharex = False, figsize=(16, 14))
    hourly[['val']].plot(ax=ax[0], legend=False)
    daily[['val']].plot(ax=ax[1], legend=False)
    monthly[['val']].plot(ax=ax[2], legend=False)

    for axA in ax:
        month = matplotlib.dates.MonthLocator()
        monthFmt = matplotlib.dates.DateFormatter('%b')
        axA.xaxis.set_major_locator(month)
        axA.xaxis.set_major_formatter(monthFmt)
        for item in axA.get_xticklabels():
            item.set_rotation(0)

    sns.despine()
    plt.tight_layout()
    return f, ax

plot2(hourly, daily, monthly)

The resulting figure shows the desired formatting for the second and third plots, but not the first plot. 结果图显示了第二个和第三个图的所需格式,但没有显示第一个图。 Figure showing the first plot is not formatted properly, but the second and third plots are formatted properly 该图显示了第一幅图的格式不正确,但是第二幅和第三幅图的格式正确

I am using Python 3.5 我正在使用Python 3.5

Seems like pandas has some problems. 好像熊猫有一些问题。 Using matplolib directly works better: 直接使用matplolib效果更好:

def plot2(hourly, daily, monthly):
    f, ax = plt.subplots(3, 1, sharex = False, figsize=(16, 14))
    ax[0].plot(hourly.index, hourly[['val']])
    ax[1].plot(daily.index, daily[['val']])
    ax[2].plot(monthly.index, monthly[['val']])

    for axA in ax[::-1]:
        month = matplotlib.dates.MonthLocator()
        monthFmt = matplotlib.dates.DateFormatter('%b')
        axA.xaxis.set_major_locator(month)
        axA.xaxis.set_major_formatter(monthFmt)
        for item in axA.get_xticklabels():
            item.set_rotation(0)

    sns.despine()
    plt.tight_layout()
    return f, ax

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM