如何在附带的图像中创建条形图?

发布于 2025-02-07 06:13:15 字数 599 浏览 0 评论 0原文

我想创建一个条形图的子图,其中“总计”是Y轴,而“植物”是X轴。同样,“品牌”将是传奇人物,因此在这种情况下,三个不同的“品牌”的3个不同图表。每个组%总计高达100%。我从下面的代码开始,但被卡住了。请参阅下面的数据示例和下图;

import pandas as pd
import numpy as np
df = pd.DataFrame({
    'brand':['A','A', 'A', 'B','B', 'B' ,'C','C', 'C'],
    'plants':[0, 1, 2, 0,1,2,0,1,2],
    '% of total':[80, 12, 8, 67, 18, 5,35, 40,25],
    
    })

plt.figure(figsize=(10, 10))
for i, brand in enumerate(['A', 'B', 'C']):

I would like to create a subplot of bar chart where '% of total' is the y-axis and 'plants' is the x-axis. Also 'brand' will be legend, so in this case 3 different charts for the 3 different 'brands'. Each groups % adds up to 100%. I started with the code below, but got stuck. Please see a sample of the data below and image below;

import pandas as pd
import numpy as np
df = pd.DataFrame({
    'brand':['A','A', 'A', 'B','B', 'B' ,'C','C', 'C'],
    'plants':[0, 1, 2, 0,1,2,0,1,2],
    '% of total':[80, 12, 8, 67, 18, 5,35, 40,25],
    
    })

plt.figure(figsize=(10, 10))
for i, brand in enumerate(['A', 'B', 'C']):

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

◇流星雨 2025-02-14 06:13:15

您可以使用seaborn

# Python env: pip install seaborn
# Anaconda env: conda install seaborn
import seaborn as sns
import matplotlib.pyplot as plt

sns.catplot(x='plants', y='% of total', col='brand', data=df, kind='bar')
plt.show()

输出:

”在此处输入图像说明”

You can use seaborn and catplot:

# Python env: pip install seaborn
# Anaconda env: conda install seaborn
import seaborn as sns
import matplotlib.pyplot as plt

sns.catplot(x='plants', y='% of total', col='brand', data=df, kind='bar')
plt.show()

Output:

enter image description here

手心的海 2025-02-14 06:13:15

这需要在循环中吗?您可以简单地使用Pandas抓住相关行。

例如:

my_A_df = df[df['brand'] == A]
plt.hist(my_A_df)
plt.bar(my_A_df['plants'], my_A_df['% of total'])

这将用于为每个生成一个小号。不确定这是否在问题的范围内,但很乐意在必要时进行编辑。

Does this need to be in a for loop? You could simply grab the relevant rows using pandas.

For example:

my_A_df = df[df['brand'] == A]
plt.hist(my_A_df)
plt.bar(my_A_df['plants'], my_A_df['% of total'])

This will work for generating a barplot for each. Not sure if this is within the bounds of your problem but happy to edit if necessary.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文