【问题标题】:Seaborn catplot Sort by Count columnSeaborn catplot 按计数列排序
【发布时间】:2021-05-12 07:35:52
【问题描述】:

问题

我的数据如下所示:

Month Product SalesCount
1 4 94
1 6 38
1 2 56
1 7 47

我想要:

  • 显示直方图并按SalesCount 从高到低对它们进行排序。
  • 显示所有标签和标题。

我的尝试

import numpy as np
import seaborn as sns

rng = np.random.default_rng()

dft = pd.DataFrame({'Month': 1,
                    'Product': rng.choice(30, size=30, replace=False),
                    'SalesCount': np.random.randint(1, 100, 30),
                    })

# Try to sort the dataframe
#dft = dft.sort_values(by=['SalesCount'])

print(dft)

g = sns.catplot(data=dft, kind='bar', x='Product', y='SalesCount', height=6, aspect=1.8, facecolor=(0.3,0.3,0.7,1))
#, order=dft[['Product', 'SalesCount']].index
(g.set_axis_labels('Product', 'Count')
    .set_titles('test'))

显示类似于此的图表:

我尝试先对数据框进行排序(dft = dft.sort_values(by=['SalesCount'])),并将order 参数(order=dft[['Product', 'SalesCount']].index)添加到sns.catplot 方法中。这两种尝试都不会对直方图进行排序。

我遇到的第二个问题是添加标题。我在FacetGrid(来自sns.catplot)实例中尝试了.set_titles('test'),但标题不会显示。

谢谢!

【问题讨论】:

  • 我认为在尝试传递order 时,您需要在获取索引之前对值进行排序?否则索引(可能)按升序排列?

标签: python matplotlib seaborn data-visualization visualization


【解决方案1】:

您可能需要将Product 列设为字符串而不是整数。这应该可以。

import numpy as np
import pandas as pd
import seaborn as sns

rng = np.random.default_rng()

dft = pd.DataFrame({'Month': 1,
                    'Product': rng.choice(30, size=30, replace=False),
                    'SalesCount': np.random.randint(1, 100, 30),
                    })

# Try to sort the dataframe
dft = dft.sort_values(by=['SalesCount'])
dft['Product'] = dft['Product'].astype(str)


print(dft)
g = sns.catplot(data=dft, kind='bar', x='Product', y='SalesCount', height=6, aspect=1.8, facecolor=(0.3,0.3,0.7,1))
#, order=dft[['Product', 'SalesCount']].index
(g.set_axis_labels('Product', 'Count')
    .set_titles('test'))

【讨论】:

  • 谢谢@Chris...你知道为什么它必须是str吗?我认为 Seaborn 也应该能够按整数排序..?
  • @stack247 不完全确定,您可能需要查看源代码,或者至少三遍检查文档以了解为什么会发生这种行为
猜你喜欢
  • 2023-01-17
  • 2021-12-27
  • 1970-01-01
  • 2019-11-10
  • 1970-01-01
  • 2019-01-20
  • 1970-01-01
  • 2020-11-26
  • 1970-01-01
相关资源
最近更新 更多