python - 自动创建未分组条形图的功能

标签 python pandas numpy matplotlib

这可能是重复的,但请注意我需要一个未分组条形图的解决方案。

这是我的可重现示例:

import pandas as pd
import numpy as np

#generate data
np.random.seed(123)
df = pd.DataFrame({ 
    'sex':np.random.choice(['male', 'female'], 500, p=[0.4, 0.6]),
    'country':np.random.choice(['US', 'UK', 'Canada'], 500, p=[0.2, 0.5, 0.3]),
    'age':np.random.normal(40,5,500).round(),
    'grade':np.random.choice(['A', 'B'], 500),
    'religion':np.random.choice(['christian', 'muslim', 'none'], 500),
    'education':np.random.choice(['bachelor', 'master', 'doctorate'], 500, p=[0.7, 0.2, 0.1])
     })

#define function to create percentage bar plot
def catbars (a):
    x = ((a.value_counts(normalize=True, ascending=True))*100).plot.barh()
    print (x)

catbars(df.country)

输出:

enter image description here

现在我想要一个类似的函数,但它将生成 6 个单独的图,每个变量对应一个(性别、国家/地区、年龄等)。我怎样才能做到这一点?

最佳答案

这个怎么样?

ncols = 3
nrows = int(np.ceil(df.shape[1] / ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols,
                         figsize=(4*ncols, 3*nrows), sharex=True)
for ax, (name, g) in zip(axes.ravel(), df.items()):
    (g.value_counts(normalize=True, ascending=True) * 100).plot.barh(ax=ax)
    ax.title.set_text(name)
plt.tight_layout()

v1

注意:作为一项改进,您可以选择按值而不是按流行率对数字列(例如示例中的 age)进行排序。因此:

ncols = 3
nrows = int(np.ceil(df.shape[1] / ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols,
                         figsize=(4*ncols, 3*nrows), sharex=True)
for ax, (name, g) in zip(axes.ravel(), df.items()):
    z = g.value_counts(normalize=True, ascending=True) * 100
    if isinstance(z.index, (pd.Float64Index, pd.Int64Index)):
        z = z.sort_index(ascending=False)  # might make more sense for numerical categories
    z.plot.barh(ax=ax)
    ax.title.set_text(name)
plt.tight_layout()

v2

关于python - 自动创建未分组条形图的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66078476/

相关文章:

python - 正确使用 fftw fft

python - 在 azure 中哪里可以找到 "storage_account_name","storage_account_key","storage_container_name"?

python - Pandas 使列成为 bool 值并删除不是的行

python - 扩展和合并 Pandas 数据框

python - 在数组中转置数组

python - 导入我的 'random' 文件时脚本失败

python - 从 Python2 升级到 Python3 时的字符串/字节问题

python - 如何映射两个数据帧并保持一个数据帧的值相同

python - 在 Ubuntu 上运行 Python 机器人(找不到文件或目录?)

python - 如何在python中调整直方图上的字体大小