Python,Seaborn:用零值绘制频率

Python, Seaborn: Plotting frequencies with zero-values

我有一个 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),并显示 zero/empty 个用于缺失刻度实例的容器,而不是简单地显示下一个数据可用的 bin。

编辑:

数据 (rated.year) 看起来像这样:

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 值计数必须为零。目前情节看起来像:

考虑 seaborn barplot 通过创建一个重新索引的系列投射到数据框:

# 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')

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

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()