首页 > 解决方案 > 为什么 ggplot geom_area 在尝试根据聚合数据绘制堆积面积图时为空?

问题描述

我正在尝试创建一个堆叠区域图,以指示分配主题的每月/每年推文的比例。我的数据框有三列;tweet_time,主题,计数。下面粘贴了一个 head()。我已经查看了类似的问题,例如下面的问题,但在这种情况下,它们各自的解决方案并未提供解决方案。 为什么我在 ggplot2 empty R ggplot2 geom_area() 中的堆积面积图不起作用

我的数据框如下:

 tweet_time Topic count
   <chr>      <chr> <dbl>
 1 01-2012    2         3
 2 01-2012    3         4
 3 01-2012    4         4
 4 01-2012    5         2
 5 01-2013    1        15
 6 01-2013    2        57
 7 01-2013    3        65
 8 01-2013    4        66
 9 01-2013    5        54
10 01-2014    1         3
11 01-2014    2         7
12 01-2014    3        10
13 01-2014    4         5
14 01-2014    5         2
15 01-2015    1         3
16 01-2015    2         6
17 01-2015    3         6
18 01-2015    4         5
19 01-2015    5         8
20 01-2016    1         7

我用于情节的代码目前是:

ggplot(test, aes(x = tweet_time,y = count, fill = Topic))+
 geom_area(aes(fill= Topic, position='stack'))

我想知道这个问题是否与未按月排序的 tweet_time 列有关(即 02/2012 不是紧随 01/2012 之后)并且格式不是日期?但是,当尝试改变 as.date 时,它​​无法识别格式。

任何帮助都会很棒。

标签: rggplot2geom-area

解决方案


我认为这里有三个问题可能会导致您的问题或导致一个问题:

  1. 日期不是日期格式

我添加mutate(tweet_time = lubridate::dmy(paste(1, tweet_time))) %>%转换为日期,这将更自动地与 ggplot2 一起工作

  1. 缺少组合

当从系列中排除零时,面积图可能会错误地显示,因为 ggplot 是否加入存在的数据点(它的作用)与假设缺失点表示零(通常是我们想要的)是模棱两可的。您可以添加 tidyr::complete(tweet_time, Topic, fill = list(count = 0)) %>%以添加这些。

  1. 填充为整数

Error: Aesthetics can not vary with a ribbon对于面积图,如果填充是整数而不是字符或因子,ggplot 可能会抛出。我不完全确定为什么会发生这种情况以及是否有理由以这种方式工作,但最简单的解决方法是让它填充一个角色或因素。

下面的代码对我有用:

library(tidyverse)
data.frame(
  stringsAsFactors = FALSE,
        tweet_time = c("01-2012","01-2012","01-2012",
                       "01-2012","01-2013","01-2013","01-2013","01-2013",
                       "01-2013","01-2014","01-2014","01-2014","01-2014",
                       "01-2014","01-2015","01-2015","01-2015","01-2015",
                       "01-2015","01-2016"),
             Topic = c(2L,3L,4L,5L,1L,2L,3L,4L,
                       5L,1L,2L,3L,4L,5L,1L,2L,3L,4L,5L,1L),
             count = c(3L,4L,4L,2L,15L,57L,65L,
                       66L,54L,3L,7L,10L,5L,2L,3L,6L,6L,5L,8L,7L)
) %>%
  tidyr::complete(tweet_time, Topic, fill = list(count = 0)) %>%
  mutate(tweet_time = lubridate::dmy(paste(1, tweet_time))) %>%
  ggplot(aes(tweet_time, count, fill = as.character(Topic))) +
  geom_area(position = 'stack')

在此处输入图像描述


推荐阅读