【问题标题】:Python, Seaborn: Plotting frequencies with zero-valuesPython,Seaborn:用零值绘制频率
【发布时间】:2018-01-03 07:11:54
【问题描述】:

我有一个 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。

编辑:

数据 (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 值的 count 必须为零。目前情节如下:

【问题讨论】:

  • 这大致创造了我想要的东西 ...它不适合我们,因为我们无权访问您的数据。请提供 rated.year 的示例。
  • 是的,你是对的,我很抱歉。我添加了一个数据可能是什么样子的示例。
  • 选项 1) 使 year 成为一个分类对象,将所有可能的年份作为类别。选项 2) 将您想要查看的所有年份的列表传递给 order 参数。
  • @mwaskom - 请作为答案发布。
  • @Parfait 你不需要删除你的答案。它是正确的并且肯定有一些价值,因为它适用于比 sns.countplot 更广泛的范围。与更简单的解决方案进行比较也有助于其他人了解问题。

标签: python pandas matplotlib seaborn


【解决方案1】:

我使用 cmets 中 @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()

【讨论】:

    【解决方案2】:

    考虑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')
    

    【讨论】:

    • 这太过分了。
    • 这就是为什么我要你回答。
    猜你喜欢
    • 2021-12-28
    • 2020-10-13
    • 2014-07-08
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    • 2020-10-28
    相关资源
    最近更新 更多