Python 多列的长方体图
我的数据帧(熊猫的结构)如上所示 现在,我想在单独的画布上为每个特性制作箱线图。分离条件为第一列。我有类似的柱状图(代码如下),但我不能为箱线图制作工作版本Python 多列的长方体图,python,pandas,boxplot,Python,Pandas,Boxplot,我的数据帧(熊猫的结构)如上所示 现在,我想在单独的画布上为每个特性制作箱线图。分离条件为第一列。我有类似的柱状图(代码如下),但我不能为箱线图制作工作版本 hist_params = {'normed': True, 'bins': 60, 'alpha': 0.4} # create the figure fig = plt.figure(figsize=(16, 25)) for n, feature in enumerate(features): # add sub plo
hist_params = {'normed': True, 'bins': 60, 'alpha': 0.4}
# create the figure
fig = plt.figure(figsize=(16, 25))
for n, feature in enumerate(features):
# add sub plot on our figure
ax = fig.add_subplot(features.shape[1] // 5 + 1, 6, n + 1)
# define range for histograms by cutting 1% of data from both ends
min_value, max_value = numpy.percentile(data[feature], [1, 99])
ax.hist(data.ix[data.is_true_seed.values == 0, feature].values, range=(min_value, max_value),
label='ghost', **hist_params)
ax.hist(data.ix[data.is_true_seed.values == 1, feature].values, range=(min_value, max_value),
label='true', **hist_params)
ax.legend(loc='best')
ax.set_title(feature)
上述代码产生如下输出(仅附加部分):
可以很好地实现自动化:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'is_true_seed': np.random.choice([True, False], 10),
'col1': np.random.normal(size=10),
'col2': np.random.normal(size=10),
'col3': np.random.normal(size=10)})
fig, ax = plt.subplots(figsize=(10, 10))
df.boxplot(['col1', 'col2', 'col3'], 'is_true_seed', ax)
第一个参数告诉熊猫哪些列要绘制,第二个参数告诉熊猫哪些列要分组(您称之为分离条件),第三个参数告诉熊猫哪些轴要绘制
列出除要分组的列之外的所有列可能会变得单调乏味,但可以通过省略第一个参数来避免。然后,您必须明确命名其他两个:
df.boxplot(by='is_true_seed', ax=ax)