如何在Python或Excel中制作这样的histplot? [包括屏幕截图]

问题描述 投票:0回答:1

我想在Python或Excel中制作这样的“比较直方图”。有人可以帮我记住如何画它吗? 在示例中,我将图表移得彼此更近,但我希望它是一个图表 在此输入图片描述

我尝试在Excel中使用简单的绘图,但它无法在一张图表上添加三个示例

excel matplotlib seaborn histogram
1个回答
0
投票

您可以使用

pandas
matplotlib
在 python 中实现以下功能:

Stacked bar plot per month and name

考虑以下数据:

data = [
    {"month": "May", "name": "Alex", "fruit": "Apple", "apple": 334, "cherry": 50},
    {"month": "May", "name": "Kristy", "fruit": "Apple", "apple": 748, "cherry": 76},
    {"month": "June", "name": "Alex", "fruit": "Apple", "apple": 229, "cherry": 54},
    {"month": "June", "name": "Kristy", "fruit": "Apple", "apple": 167, "cherry": 17},
    {"month": "July", "name": "Alex", "fruit": "Apple", "apple": 272, "cherry": 47},
    {"month": "July", "name": "Kristy", "fruit": "Apple", "apple": 902, "cherry": 79},
]
df = pd.DataFrame(data)
print(df)
  month    name  fruit  apple  cherry
0   May    Alex  Apple    334      50
1   May  Kristy  Apple    748      76
2  June    Alex  Apple    229      54
3  June  Kristy  Apple    167      17
4  July    Alex  Apple    272      47
5  July  Kristy  Apple    902      79

以下代码将输出上图:

import matplotlib.pyplot as plt
import pandas as pd

fig, axes = plt.subplots(
    ncols=3,
    sharey=True,
    gridspec_kw={"wspace": 0},
    figsize=(15, 5),
)

for ax, (month, data) in zip(axes, df.groupby("month")):
    data.plot(
        kind="bar",
        x="name",
        y=["apple", "cherry"],
        stacked=True,
        ax=ax,
        rot=0,
    )

    # Write the month centered underneath the x-axis
    ax.text(
        0.5,
        -0.1,
        month,
        horizontalalignment="center",
        verticalalignment="center",
        transform=ax.transAxes,
    )

# Remove x-axis label
for ax in axes:
    ax.set_xlabel("")

    # Remove y axis except first axis
    if not ax.get_subplotspec().is_first_col():
        ax.get_yaxis().set_visible(False)

    # Remove legend except last axis
    if not ax.get_subplotspec().is_last_col():
        ax.get_legend().remove()

plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.