Pandas secondary y axis for boxplots

走远了吗. 提交于 2019-12-25 03:33:03

问题


I'd like to use a secondary y-axis for some boxplots in pandas, but it doesn't seem available.

import numpy as np
import pandas as pd

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

Now, using the default line plot it's easy enough to plot to a second y-axis:

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

But if I use boxplot style, it doesn't work:

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

Is there any way (maybe through matplotlib) I can get pandas to plot 2 axes for boxplot? Using the boxplot() method would be preferable, but I'll take plot(). Thanks.


回答1:


Actually not that hard with 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)

There's still some cleanup with the styling, ticklabels etc. But that should get you started.



来源:https://stackoverflow.com/questions/28840036/pandas-secondary-y-axis-for-boxplots

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!