【问题标题】:Normalized and percentage plots using matplotlib使用 matplotlib 进行归一化和百分比图
【发布时间】:2021-12-09 20:12:26
【问题描述】:

我目前使用的数据集显示了客户及其类别。

Customer     Class
4124          A
4123          A
532           B
4512          A
5325          B
642           C
5345          A

我正在使用 matplotlib 绘制频率条形图:

class_f=df.groupby(['Class']).size().reset_index(name='Frequency').sort_values('Frequency', ascending=False)
plt.bar(class_f['Class'].astype(str), class_f['Frequency'])
plt.show()

但我想使用归一化图和 y 轴上的百分比值来可视化结果。 对于百分比值,我一直在尝试使用 mtick。 对于标准化图,我发现了很多堆叠图和使用 seaborn 的示例。我想知道如何使用 matplotlib 做同样的事情。

【问题讨论】:

  • 感谢 JohanC。如果您可以添加答案,我将非常乐意更改标签并将其作为解决方案接受 :) 将 seaborn 也用于标准化绘图会很好吗?
  • 非常感谢 JohanC​​pan>

标签: python pandas matplotlib


【解决方案1】:

以下代码说明了 3 个不同的图:

  • matplotlib 条形图从聚合数据框创建,降序排列
  • seaborn histplot with stat='percent'(使用遇到类的顺序)
  • seaborn histplot with multiple='fill' 显示每个类的相对比例;通常使用来自另一列的 x 轴;如果不是,则可以使用一个虚拟的零数组来仅具有一个 x 位置

import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
import seaborn as sns
import pandas as pd
import numpy as np

df = pd.DataFrame({'Customer': np.random.randint(1000, 10000, 30),
                   'Class': np.random.choice(['A', 'B', 'C'], 30)})
class_f = df.groupby(['Class']).size().reset_index(name='Frequency').sort_values('Frequency', ascending=False)

fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(14, 4))
ax1.bar(class_f['Class'], class_f['Frequency'] / class_f['Frequency'].sum() * 100)
ax1.yaxis.set_major_formatter(PercentFormatter(100, decimals=0))

sns.histplot(data=df, x='Class', stat='percent', ax=ax2)
ax2.yaxis.set_major_formatter(PercentFormatter(100, decimals=0))

sns.histplot(data=df, x=np.zeros(len(df)), stat='percent', hue='Class', multiple='fill', ax=ax3)
ax3.yaxis.set_major_formatter(PercentFormatter(1))
ax3.set_xticks([])

plt.tight_layout()
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    相关资源
    最近更新 更多