python - 我正在尝试使用 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')
解决方案
只需使用行数和列数设置 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()
推荐阅读
- python - 具有多个参数的 Python UDF
- react-native - 如何比较 onPress 中的两个变量?
- java - 如何使用 RESTful 为 Spring Security Role Based Access Authorization 填充 MySQL 表?
- php - 如何在不直接在 Laravel 5.6 中编辑的情况下覆盖 AuthenticatesUsers 供应商文件的loggedOut?
- android - 如何在 Android + Kotlin 上使用 AWS Amplify 登录用户?
- java - Serializable class not found 移动类包时抛出CLASSNAME错误(即使在类中声明了serialVersionUID)
- c++ - 减小核心转储大小 MacOS
- powershell - 使用正则表达式读取用于监控的日志文件
- clips - 检查 CLIPS 中的多个事实
- java - 简单的计数器应用程序在启动时崩溃而没有任何错误