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