【问题标题】:Seaborn barchart y values not summed as expectedSeaborn 条形图 y 值未按预期求和
【发布时间】:2021-03-25 21:38:43
【问题描述】:

为什么我的 Seaborn 条形图中的 y 值没有正确求和?下表包含预期值,您可以在下图中看到它们不匹配。代码在最后。这不是 Seaborn bar plot y axis has different values than expected 的重复,因为那里的问题与日期时间格式有关。

df.groupby(['Category', 'Sub-Category'])['Profit'].sum()

Category    Sub-Category
Furniture   Bookcases        42.4
            Tables          301.3
Supplies    Labels          285.5
            Paper            82.7
Technology  Copiers         -42.1
            Phones          155.0

g = sns.FacetGrid(data=df, col='Category', sharex=False, sharey=False)
g.map_dataframe(sns.barplot, x='Sub-Category', y='Profit', ci=None)

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

### Create dummy data
cat = [ 'Furniture','Supplies','Furniture',
        'Supplies','Furniture','Technology',
        'Technology','Technology','Supplies',
        'Furniture','Supplies','Furniture',
        'Supplies','Furniture', 'Technology',
        'Technology','Technology','Supplies',
]

scat = ['Bookcases','Labels','Tables',
        'Labels','Bookcases','Copiers',
        'Copiers','Phones','Labels',
        'Bookcases','Paper','Tables',
        'Paper','Tables', 'Phones',
        'Phones','Copiers','Paper',
]

prof = [41.1,219.5,6.8,
        -383,2.5, 12.1,
        -71.2,16,449,
        -1.2,9,313,
        92,-18.5,132,
        7,17,-18.3,
]

df = pd.DataFrame(list(zip(cat, scat, prof)), 
                    columns =['Category', 'Sub-Category', 'Profit']
                    )

print(df.groupby(['Category', 'Sub-Category'])['Profit'].sum())
g = sns.FacetGrid(data=df, col='Category', sharex=False, sharey=False)
g.map_dataframe(sns.barplot, x='Sub-Category', y='Profit', ci=None)
plt.show()


顺便说一句:我也尝试了 catplot,但我无法关闭空类别。例如,“纸”仍显示在“家具”类别的 x 轴上。我使用了g = sns.catplot(data=df, x='Sub-Category', y='Profit', col='Category', kind='bar', ci=None,) 并尝试添加sharex=Falsefacet_kws={"dropna": True},但这不起作用。并且它仍然显示与上例相同的 y 轴值。

【问题讨论】:

  • 你为什么期望它们被求和?

标签: python pandas matplotlib seaborn


【解决方案1】:

sns.barplot 不求和。它只显示其输入值的条形图。如果多个条形图最终位于同一位置,则取平均值并显示置信区间。

要显示总和,需要提供一个包含总和的数据框。 groupby 结果不能直接使用,因为 seaborn 期望其数据在显式列中。 .reset_index() 将索引转换为实列。

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

cat = ['Furniture', 'Supplies', 'Furniture', 'Supplies', 'Furniture', 'Technology', 'Technology', 'Technology',
       'Supplies', 'Furniture', 'Supplies', 'Furniture', 'Supplies', 'Furniture', 'Technology', 'Technology',
       'Technology', 'Supplies', ]
scat = ['Bookcases', 'Labels', 'Tables', 'Labels', 'Bookcases', 'Copiers', 'Copiers', 'Phones', 'Labels', 'Bookcases',
        'Paper', 'Tables', 'Paper', 'Tables', 'Phones', 'Phones', 'Copiers', 'Paper']
prof = [41.1, 219.5, 6.8, -383, 2.5, 12.1, -71.2, 16, 449, -1.2, 9, 313, 92, -18.5, 132, 7, 17, -18.3, ]
df = pd.DataFrame({'Category': cat, 'Sub-Category': scat, 'Profit': prof})

df_summed = df.groupby(['Category', 'Sub-Category'])['Profit'].sum().reset_index()
g = sns.FacetGrid(data=df_summed, col='Category', sharex=False, sharey=False)
g.map_dataframe(sns.barplot, x='Sub-Category', y='Profit')
g.map(plt.axhline, y=0, color='black') # horizontal line at y=0
plt.tight_layout()
plt.show()

要使用catplot 创建绘图,还需要将sharex 设置为False。 (请注意,您需要设置一个明确的颜色,因为catplot 默认通过它们的 x 位置为条形着色,在 sharex=False 的情况下,每个 supblot 都不同。)

在cmets中提到,barplot有一个参数estimator可以设置为sum,需要关闭ci。这是一个例子:

g = sns.catplot(kind='bar', data=df, x='Sub-Category', y='Profit', estimator=sum, ci=None,
                col='Category', sharex=False, color='dodgerblue')
g.map(plt.axhline, y=0, color='navy')
g.despine(bottom='True')
for ax in g.axes.flat:
    ax.tick_params(axis='both', length=0)
    ax.grid(axis='y', color='grey', ls=':', zorder=0)

【讨论】:

  • 我认为,如果您使用 estimator=sum,则可以使用原始数据框获得所需的结果,但我很好奇为什么 OP 给人的印象是默认行为。
  • 我尝试了类似的方法,但置信区间变得非常长。这让我很困惑。它们在求和时是否具有统计意义? (默认情况下关闭它们可能也会令人困惑。)
  • 这里总和的 CI 变大并不奇怪,因为数据集很小且方差很大。我认为一般而言,随机观察总和的 CI 在统计上是有效的,尽管在许多实际情况下它们并没有真正意义。
猜你喜欢
  • 2020-02-16
  • 2019-02-18
  • 2019-07-23
  • 1970-01-01
  • 2019-01-23
  • 2022-09-23
  • 2015-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多