【问题标题】:Pandas secondary y axis for boxplots箱线图的熊猫次要y轴
【发布时间】:2015-05-04 14:09:51
【问题描述】:

我想为 pandas 中的一些箱线图使用辅助 y 轴,但它似乎不可用。

import numpy as np
import pandas as pd

data = np.random.random((10, 5))
data[:,-1] += 10  # offset one column
df = pd.DataFrame(data)

现在,使用默认线图很容易绘制到第二个 y 轴:

df.plot(kind='line', secondary_y=[4])

但是如果我使用箱线图样式,它就不起作用了:

df.plot(kind='box', secondary_y=[4])

有什么方法(可能通过 matplotlib)我可以让 pandas 为箱线图绘制 2 个轴吗?使用boxplot() 方法会更好,但我会采用plot()。谢谢。

【问题讨论】:

    标签: python pandas boxplot


    【解决方案1】:

    其实用 matplotlib 没那么难。

    In [22]: fig, ax = plt.subplots()
    
    In [23]: df[[0, 1, 2, 3]].plot(kind='box', ax=ax)
    Out[23]: <matplotlib.axes._subplots.AxesSubplot at 0x4890978>
    
    In [24]: ax2 = ax.twinx()
    
    In [25]: ax2.boxplot(df[4], positions=[4])
    
    In [27]: ax.set_xlim(0, 5)
    Out[27]: (0, 5)
    

    样式、刻度标签等仍有一些清理工作。但这应该可以帮助您入门。

    【讨论】:

    • 优秀。 positions 参数是我在挖掘时没有看到的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 2021-07-11
    • 2018-11-30
    • 2017-09-09
    • 2014-11-05
    • 2020-03-13
    • 2021-10-14
    相关资源
    最近更新 更多