我正在尝试创建一个堆积面积图来指示指定主题每月/每年的推文比例。我的数据框有三列; tweet_time、主题、计数。下面粘贴了其 head() 。 我看过类似的问题,例如下面的问题,但他们各自的解决方案在这种情况下没有提供修复。 Why is my stacked area graph in ggplot2 empty R ggplot2 geom_area() not working
我的数据框如下:
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 时,它无法识别该格式。
任何帮助都会很棒。
最佳答案
我认为这里存在三个问题可能会导致您的问题或导致以下问题:
- 日期不是日期格式
我添加 mutate(tweet_time = lubridate::dmy(paste(1, tweet_time))) %>%
来转换为日期,这将更自动地与 ggplot2 配合使用
- 缺少组合
tidyr::complete(tweet_time, Topic, fill = list(count = 0)) %>%
来添加这些内容。
- 填写为整数
对于面积图,如果填充是整数而不是字符或因子,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::my(tweet_time))) %>%
ggplot(aes(tweet_time, count, fill = as.character(Topic))) +
geom_area(position = 'stack')
关于r - 当尝试根据聚合数据绘制堆积面积图时,为什么 ggplot geom_area 为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67795547/