pandas boxp共享轴的不同ylim

2024-06-27 23:58:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个分组熊猫箱图,以(2,2)网格排列:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.rand(140, 4), columns=['A', 'B', 'C', 'D'])
df['models'] = pd.Series(np.repeat(['model1','model2', 'model3', 'model4', 'model5', 'model6', 'model7'], 20))
bp = df.boxplot(by="models",layout=(2,2),figsize=(6,8))
plt.show()

enter image description here

我现在只想更改第二行的ylim。在

我的想法是补充:

^{pr2}$

或者

[ax_tmp.set_ylim(-10,10) for ax_tmp in np.asarray(bp)[1,:]]

但它们都改变了所有子批次的ylim。 这可能是因为分享。但我不知道该如何摆脱它。在

我的问题和这个有点关系:pandas boxplot, groupby different ylim in each subplot但在我看来不是重复的。此外,解决方案在这里也不容易适用。在

更新:理想情况下,行应该共享一个公共y,而不是每个行都有自己的y


Tags: inimportpandasdfmodelsasnpplt
1条回答
网友
1楼 · 发布于 2024-06-27 23:58:20

解决方案是将一个fig,axes传递给熊猫的boxplot,它们是用sharey=False定制的:

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

df = pd.DataFrame(np.random.rand(140, 4), columns=['A', 'B', 'C', 'D'])
df['models'] = pd.Series(np.repeat(['model1','model2', 'model3', 'model4', 'model5', 'model6', 'model7'], 20))
fig, ax_new = plt.subplots(2,2, sharey=False)
bp = df.boxplot(by="models",ax=ax_new,layout=(2,2),figsize=(6,8))
[ax_tmp.set_xlabel('') for ax_tmp in ax_new.reshape(-1)]
[ax_tmp.set_ylim(-2, 2) for ax_tmp in ax_new[1]]
fig.suptitle('New title here')
plt.show()

结果:

enter image description here

如果你想按行共享。此代码适用于您:

^{pr2}$

如您所见,仅使用all_axes[1][0].set_ylim(-2,2)更改第二行中第一个轴的ylim,整行都被更改了。all_axes[1][1].set_ylim(-2,2)也会这样做,因为它们有一个共享的y轴。在

enter image description here

如果希望x轴仅位于最后一行,y轴标签仅位于第一列,只需将循环更改为:

for i in range(layout[0]):
    tmp_row_axes = []
    for j in range(layout[1]):
         if j!=0 :
             exec "tmp_ax = fig.add_subplot(%d%d%d, sharey=tmp_row_axes[0])"%(layout[0],layout[1],counter)
             tmp_ax.get_yaxis().set_visible(False)
         else:
             exec "tmp_ax=fig.add_subplot(%d%d%d)" % (layout[0], layout[1], counter)
         if i!=layout[1]-1 :
             tmp_ax.get_xaxis().set_visible(False)
         tmp_row_axes.append(tmp_ax)
         counter+=1
    all_axes.append(tmp_row_axes)

结果:

enter image description here

相关问题 更多 >