Python、Seaborn:用零值绘制频率

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

我有一个 Pandas 系列,我想为其绘制计数值。这大致创建了我想要的:

dy = sns.countplot(rated.year, color="#53A2BE")
axes = dy.axes
dy.set(xlabel='Release Year', ylabel = "Count")
dy.spines['top'].set_color('none')
dy.spines['right'].set_color('none')
plt.show()

问题在于数据丢失。收视率有31年,但时间跨度超过42年。这意味着应该有一些未显示的空箱。有没有办法在 Seaborn/Matplotlib 中配置它?我应该使用其他类型的图表,还是有其他解决方案?

我考虑过是否可以将其配置为时间序列,但我对评级量表也有同样的问题。因此,在 1-10 的范围内,例如4 可能为零,因此“4”不在 Pandas 数据系列中,这意味着它也不会显示在图表中。

我想要的结果是 x 轴上的满刻度,y 轴上的计数(步长为 1),并显示刻度缺失实例的零/空箱,而不是简单地显示下一个其数据可用的 bin。

编辑:

数据(额定年份)看起来像这样:

import pandas as pd

rated = pd.DataFrame(data = [2016, 2004, 2007, 2010, 2015, 2016, 2016, 2015,
                             2011, 2010, 2016, 1975, 2011, 2016, 2015, 2016, 
                             1993, 2011, 2013, 2011], columns = ["year"])

它有更多的值,但格式是一样的。正如你所看到的..

rated.year.value_counts()

..图中有相当多的 x 值的计数必须为零。目前情节如下:

python pandas matplotlib seaborn
2个回答
13
投票

我通过使用 @mwaskom 在我的问题的评论中建议的解决方案解决了问题。 IE。将“订单”添加到计数图中,其中包含年份的所有有效值,包括计数为零的值。这是生成图表的代码:

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

rated = pd.DataFrame(data = [2016, 2004, 2007, 2010, 2015, 2016, 2016, 2015,
                             2011, 2010, 2016, 1975, 2011, 2016, 2015, 2016, 
                             1993, 2011, 2013, 2011], columns = ["year"])

dy = sns.countplot(rated.year, color="#53A2BE", order = list(range(rated.year.min(),rated.year.max()+1)))
axes = dy.axes
dy.set(xlabel='Release Year', ylabel = "Count")
dy.spines['top'].set_color('none')
dy.spines['right'].set_color('none')
plt.show()

1
投票

通过创建转换为数据框的重新索引系列来考虑 seaborn 条形图

# REINDEXED DATAFRAME
rated_ser = pd.DataFrame(rated['year'].value_counts()
                         .reindex(
                                  range(
                                       rated.year.min(),
                                       rated.year.max()+1),
                                       fill_value=0
                                       )
                         )
                         .reset_index()

# SNS BAR PLOT
dy = sns.barplot(x='index', y='year', data=rated_ser, color="#53A2BE")
dy.set_xticklabels(dy.get_xticklabels(), rotation=90)   # ROTATE LABELS, 90 DEG.
axes = dy.axes
dy.set(xlabel='Release Year', ylabel = "Count")

dy.spines['top'].set_color('none')
dy.spines['right'].set_color('none')

© www.soinside.com 2019 - 2024. All rights reserved.