python - 结合不同范围的 Pandas 中的多个箱线图?

标签 python pandas data-visualization boxplot

我有 2 个数据集,一个代表根区 (mm),另一个代表树覆盖率 (%)。我能够并排绘制这些数据集(如下所示)。 使用的代码是:

    fig = plt.subplots(figsize = (16,7))
    ax = [
        plt.subplot(121),
        plt.subplot(122)]
    classified_data.boxplot(grid=False, rot=90, fontsize=10, ax = ax[0])
    classified_treecover.boxplot(grid=False, rot=90, fontsize=10, ax = ax[1])
    ax[0].set_ylabel('Rootzone Storage Capacity (mm)', fontsize = '12')
    ax[1].set_ylabel('Tree Cover (%)', fontsize = '12')
    ax[0].set_title('Rootzone Storage Capacity (mm)')
    ax[1].set_title('Tree Cover (%)')

enter image description here

但我想让它们与 Rootzone(在左侧 y 轴上)和 Tree cover(在右侧 y 轴上)在同一个图中,因为它们的范围不同(使用类似 双胞胎())。但我希望它们在 x 轴上堆叠在一起作为一个类(如下图所示,树盖有一个双 y 轴)。 有人可以指导我如何使用我的代码实现这一目标吗?

enter image description here

最佳答案

要在同一张图中绘制具有不同范围的两个数据集,您需要将所有值转换为相应的 z 分数(标准化您的数据)。您可以在 seabornboxplot() 函数中使用 hue 参数来并排绘制两个数据集。考虑以下使用“mpg”数据集的示例。

   displacement  horsepower origin
0         307.0       130.0    usa
1         350.0       165.0    usa
2         318.0       150.0    usa
3         304.0       150.0    usa
4         302.0       140.0    usa

import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset('mpg')

df1 = df[['displacement', 'origin']].copy()
df2 = df[['horsepower', 'origin']].copy()

# Convert values to z scores.
df1['z_score'] = df1['displacement'].\
apply(lambda x: (x - df1['displacement'].mean()) / df1['displacement'].std())
df2['z_score'] = df2['horsepower'].\
apply(lambda x: (x - df2['horsepower'].mean()) / df2['horsepower'].std())

df1.drop(['displacement'], axis= 1, inplace=True)
df2.drop(['horsepower'], axis=1, inplace=True)

# Add extra column to use it as the 'hue' parameter.
df1['value'] = 'displacement'
df2['value'] = 'horsepower'

df_cat = pd.concat([df1, df2])

ax = sns.boxplot(x='origin', y='z_score', hue='value', data=df_cat)

plt.yticks([])
ax.set_ylabel('')

# Add the left y axis.
ax1 = ax.twinx()
ax1.set_yticks(np.linspace(df['displacement'].min(), df['displacement'].max(), 5))
ax1.spines['right'].set_position(('axes', -0.2))
ax1.set_ylabel('displacement')

# Add the right y axis.
ax2 = ax.twinx()
ax2.set_yticks(np.linspace(df['horsepower'].min(), df['horsepower'].max(), 5))
ax2.spines['right'].set_position(('axes', 1))
ax2.set_ylabel('horsepower')
plt.show()

Figure

关于python - 结合不同范围的 Pandas 中的多个箱线图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58363328/

相关文章:

Python调用类函数作为其他类属性

Python Pandas : print the csv data in oder with columns

python - pandas 数据帧按类和时间戳分组

python - 使用shape或pivot_table reshape pandas数据框(堆叠每行)

python - 基于列表/字典动态更改 networkx 中箭头的大小

mongodb - 更改 1500 列数据集以便于前端操作

matlab - 使用散点图可视化大型 3D 数据集

python - 如何在 SQLite 表中存储 Python 函数?

python - Elasticsearch 词聚合中的问题

python - 为什么某些实现在Python中运行缓慢?