简体   繁体   English

如何更改按箱线图分组的熊猫中的组标题?

[英]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()

在此处输入图片说明

I would like to change the two labels Col1 and Col2 , I have tried to pass the argument labels=['Left label','Right label'] (to the matplotlib core function https://matplotlib.org/api/_as_gen/matplotlib.pyplot.boxplot.html#matplotlib.pyplot.boxplot ) but with no luck:我想更改两个标签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'])

gives me the error:给我错误:

ValueError: Dimensions of labels and X must be compatible

Try this, because boxplot here returns a NumPy array of axes, you can use each element of this NumPy array and set_title:试试这个,因为这里的 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()

You may wish to try:你不妨试试:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM