Pandas plot hist sharex=False 行为不符合预期

Sal*_*ali 7 python matplotlib pandas

我正在尝试从数据框中绘制几个系列的直方图。系列有不同的最大值:

df[[
    'age_sent', 'last_seen', 'forum_reply', 'forum_cnt', 'forum_exp', 'forum_quest'
]].max()
Run Code Online (Sandbox Code Playgroud)

返回:

age_sent       1516.564016
last_seen       986.790035
forum_reply     137.000000
forum_cnt       155.000000
forum_exp        13.000000
forum_quest      10.000000
Run Code Online (Sandbox Code Playgroud)

当我尝试绘制直方图时,我使用sharex=False, subplots=True但看起来sharex属性被忽略:

df[[
    'age_sent', 'last_seen', 'forum_reply', 'forum_cnt', 'forum_exp', 'forum_quest'
]].plot.hist(figsize=(20, 10), logy=True, sharex=False, subplots=True)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


我可以清楚地分别绘制它们中的每一个,但这不太理想。我也想知道我做错了什么。


我拥有的数据太大也无法包含在内,但很容易创建类似的内容:

ttt = pd.DataFrame({'a': pd.Series(np.random.uniform(1, 1000, 100)), 'b': pd.Series(np.random.uniform(1, 10, 100))})
Run Code Online (Sandbox Code Playgroud)

我现在有:

ttt.plot.hist(logy=True, sharex=False, subplots=True)
Run Code Online (Sandbox Code Playgroud)

检查 x 轴。我希望它是这种方式(但使用一个带有子图的命令)。

ttt['a'].plot.hist(logy=True)
ttt['b'].plot.hist(logy=True)
Run Code Online (Sandbox Code Playgroud)

tac*_*ell 5

如果平移/缩放一个轴改变另一个轴,则(最sharex有可能)会落入 mpl 并设置。

您遇到的问题是,所有直方图都使用相同的垃圾箱(这是由https://github.com/pydata/pandas/blob/master/pandas/tools/plotting.py#L2053强制执行的,如果我我正确理解了代码),因为 pandas 假设如果您使用多个直方图,那么您可能正在绘制相似数据的列,因此使用相同的分箱可以使它们具有可比性。

假设你有 mpl >= 1.5 和 numpy >= 1.11 你应该给自己写一个小辅助函数,比如

import matplotlib.pyplot as plt
import matplotlib as mpl 
import pandas as pd
import numpy as np

plt.ion()


def make_hists(df, fig_kwargs=None, hist_kwargs=None,
               style_cycle=None):
    '''

    Parameters
    ----------
    df : pd.DataFrame
        Datasource

    fig_kwargs : dict, optional
        kwargs to pass to `plt.subplots`

        defaults to {'fig_size': (4, 1.5*len(df.columns),
                     'tight_layout': True}

    hist_kwargs : dict, optional
        Extra kwargs to pass to `ax.hist`, defaults
        to `{'bins': 'auto'}

    style_cycle : cycler
        Style cycle to use, defaults to 
        mpl.rcParams['axes.prop_cycle']

    Returns
    -------
    fig : mpl.figure.Figure
        The figure created

    ax_list : list
        The mpl.axes.Axes objects created 

    arts : dict 
        maps column names to the histogram artist
    '''
    if style_cycle is None:
        style_cycle = mpl.rcParams['axes.prop_cycle']

    if fig_kwargs is None:
        fig_kwargs = {}
    if hist_kwargs is None:
        hist_kwargs = {}

    hist_kwargs.setdefault('log', True)
    # this requires nmupy >= 1.11
    hist_kwargs.setdefault('bins', 'auto')
    cols = df.columns

    fig_kwargs.setdefault('figsize', (4, 1.5*len(cols)))
    fig_kwargs.setdefault('tight_layout', True)
    fig, ax_lst = plt.subplots(len(cols), 1, **fig_kwargs)
    arts = {}
    for ax, col, sty in zip(ax_lst, cols, style_cycle()):
        h = ax.hist(col, data=df, **hist_kwargs, **sty)
        ax.legend()

        arts[col] = h

    return fig, list(ax_lst), arts

dist = [1, 2, 5, 7, 50]
col_names = ['weibull $a={}$'.format(alpha) for alpha in dist]
test_df = pd.DataFrame(np.random.weibull(dist,
                                         (10000, len(dist))),
                       columns=col_names)

make_hists(test_df)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述