首页 > 解决方案 > 我正在尝试使用 pandas 为数据框中的 5 个分类变量创建单独的条形图

问题描述

我有一个包含 4 列数据的数据框。这些列中的每一列都是包含 5 个不同值的字符变量(即 column1 包含值 A、B、C、D 或 E。column2 包含值 EXCELLENT、VERY GOOD、GOOD、AVERAGE 和 POOR。第 3 列和第 4 列相似.

我试图通过使用下面的 for 循环为每一列获取一个单独的条形图。不幸的是,它只为我提供了第 4 列的条形图。它没有提供前 3 列的条形图。不知道我做错了什么。

categorical_attribs=list(CharacterVarDF)
    
for i in categorical_attribs:
    
    CharacterVarDF [i].value_counts().plot(kind='bar')

标签: pythonpandas

解决方案


只需使用行数和列数设置 matplotlib 子图。然后在循环中,将每个柱形图分配给每个ax

import matplotlib.pyplot as plt
...

fig, axes = plt.subplots(figsize=(8,6), ncols=1, nrows=CharacterVarDF.shape[1])

for col, ax in zip(CharacterVarDF.columns, np.ravel(axes)):
    CharacterVarDF[col].value_counts().plot(kind='bar', ax=ax, rot=0, title=col)

plt.tight_layout()
plt.show()

用随机数据进行演示:

import numpy as np
import pandas as pd
from matplotlib import rc
import matplotlib.pyplot as plt

np.random.seed(52021)
env_df = pd.DataFrame({
    "planetary_boundaries": np.random.choice(
        ["ocean", "land", "biosphere", "atmosphere", 
         "climate", "soil", "ozone", "freshwater"], 50),
    "species": np.random.choice(
        ["invertebrates", "vertebrates", "plants", "fungi & protists"], 50),
    "tipping_points": np.random.choice(
        ["Arctic Sea Ice", "Greenland ice sheet", "West Antarctica ice sheet",
         "Amazon Rainforest", "Boreal forest", "Indian Monsoon", 
         "Atlantic meridional overturning circulation", 
         "West African Monsoon", "Coral reef"], 50)
})

rc('font', **{'family' : 'Arial'})
fig, axes = plt.subplots(ncols=1, nrows=env_df.shape[1], figsize=(7,7))

for col, ax in zip(env_df.columns, np.ravel(axes)):
    env_df[col] = env_df[col].str.replace(" ", "\n")
    env_df[col].value_counts(sort=False).sort_index().plot(
        kind='bar', ax=ax, color='g', rot=0,
        title=col.replace("_", " ").title(),
    )

plt.tight_layout()
plt.show()
plt.clf()
plt.close()

绘图输出


推荐阅读