如何更改 pandas grouped-by 箱线图中的组标题?

How can I change the group titles in a pandas grouped-by boxplot?

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

df = pd.DataFrame(np.random.randn(10, 3),
                  columns=['Col1', 'Col2', 'Col3'])
df['X'] = pd.Series(['A', 'A', 'A', 'A', 'A',
                     'B', 'B', 'B', 'B', 'B'])
df['Y'] = pd.Series(['A', 'B', 'A', 'B', 'A',
                     'B', 'A', 'B', 'A', 'B'])
boxplot = df.boxplot(column=['Col1', 'Col2'], by=['X', 'Y'])

plt.show()

我想更改Col1Col2这两个标签,我尝试传递参数labels=['Left label','Right label'](给matplotlib核心函数https://matplotlib.org/api/_as_gen/matplotlib.pyplot.boxplot.html#matplotlib.pyplot.boxplot)但是没有运气:

boxplot = df.boxplot(column=['Col1', 'Col2'], by=['X', 'Y'], labels=['Left label','Right label'])

给我错误:

ValueError: Dimensions of labels and X must be compatible

试试这个,因为这里的箱线图 returns 一个 NumPy 轴数组,您可以使用这个 NumPy 数组的每个元素和 set_title:

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

df = pd.DataFrame(np.random.randn(10, 3),
                  columns=['Col1', 'Col2', 'Col3'])
df['X'] = pd.Series(['A', 'A', 'A', 'A', 'A',
                     'B', 'B', 'B', 'B', 'B'])
df['Y'] = pd.Series(['A', 'B', 'A', 'B', 'A',
                     'B', 'A', 'B', 'A', 'B'])
ax = df.boxplot(column=['Col1', 'Col2'], by=['X', 'Y'])

ax[0].set_title('AAA')
ax[1].set_title('BBB')

plt.show()

您不妨试试:

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

df = pd.DataFrame(np.random.randn(10, 3),
                  columns=['Col1', 'Col2', 'Col3'])
df['X'] = pd.Series(['A', 'A', 'A', 'A', 'A',
                     'B', 'B', 'B', 'B', 'B'])
df['Y'] = pd.Series(['A', 'B', 'A', 'B', 'A',
                     'B', 'A', 'B', 'A', 'B'])
axes = df.boxplot(column=['Col1', 'Col2'], by=['X', 'Y'])
titles=['Left label','Right label']
for ax, title in zip(axes,titles):
    ax.set_title(title)