温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - How can I change the group titles in a pandas grouped-by boxplot?
boxplot pandas python

python - 如何在按箱图分组的 pandas 中更改组标题?

发布于 2021-02-08 09:57:48
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()

在此处输入图片说明

我想更改两个标签,Col1并且Col2,我尝试将参数传递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

查看更多

提问者
Alessandro Jacopson
被浏览
77
Scott Boston 2020-10-13 22:14

尝试一下,因为boxplot返回一个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()