r - geom_area 中的特定填充顺序

标签 r ggplot2

新年快乐!考虑这个简单的例子:

> df <- tibble(type = c('0_10','0_9','0_8','0_10','0_9','0_8','1_10','1_9','1_8','1_10','1_9','1_8'),
+        time = c(1,1,1,2,2,2,1,1,1,2,2,2),
+        value = c(2,3,4,2,3,6,-2,-3,-4,-2,-3,-5)) 
> df
# A tibble: 12 x 3
   type   time value
   <chr> <dbl> <dbl>
 1 0_10      1     2
 2 0_9       1     3
 3 0_8       1     4
 4 0_10      2     2
 5 0_9       2     3
 6 0_8       2     6
 7 1_10      1    -2
 8 1_9       1    -3
 9 1_8       1    -4
10 1_10      2    -2
11 1_9       2    -3
12 1_8       2    -5

我正在创建一个图,该图按 type 随着时间的推移堆叠 value 的值。我想为 0_101_10 类型获得相同的颜色,为 0_91_9 获得另一种颜色,并且0_81_8 的另一种颜色。

不幸的是,ggplot 似乎没有使用我要求的因子排序。您可以在下面看到 0_10 是紫色,而 1_10 是绿色......它们应该具有相同的颜色。

mylevels = c('0_10','0_9','0_8','1_10','1_9','1_8')

df %>% 
  ggplot(aes(x = time)) +
  geom_area(inheris.aes = FALSE,
            data = . %>%  dplyr::filter(str_detect(type, '0_')),
            aes(y = value, 
                fill = factor(type, levels = mylevels)),
            position = 'stack', color = 'black')+
  scale_fill_viridis_d() +
  geom_area(inheris.aes = FALSE,
            data = . %>%  dplyr::filter(str_detect(type, '1_')),
            aes(y = value, fill = factor(type, levels = mylevels)),
            position = 'stack', color = 'black')

enter image description here

有什么想法吗? 谢谢!

最佳答案

我会根据您的类型列中的最后一个数字创建一个新列以进行填充。并按类型创建组。

library(tidyverse)
df <- tibble(type = c('0_10','0_9','0_8','0_10','0_9','0_8','1_10','1_9','1_8','1_10','1_9','1_8'), time = c(1,1,1,2,2,2,1,1,1,2,2,2), value = c(2,3,4,2,3,6,-2,-3,-4,-2,-3,-5)) 

df %>% 
  mutate(colvar = gsub("^*._","", type)) %>%
  ggplot(aes(x = time)) +
  geom_area(aes(y = value, 
                fill = colvar, 
                group = type),
            position = 'stack', color = 'black') +
  scale_fill_viridis_d() 

如果你想可视化你的第一个“类型数字”的信息,你需要使它成为另一种美学,例如 alpha:

更新新的 colvar 变量作为具有有序水平的因子

df %>% 
  mutate(colvar = factor(gsub("^*._","", type), levels = 8:10), 
         alphavar =  as.integer(substr(type, 1, 1))) %>%
  ggplot(aes(x = time)) +
  geom_area(aes(y = value, 
                fill = colvar, 
                group = type, 
                alpha = alphavar),
            position = 'stack', color = 'black') +
  scale_fill_viridis_d() +
  scale_alpha_continuous(breaks = 0:1, range = c(0.7,1) )

关于r - geom_area 中的特定填充顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65523826/

相关文章:

pointers - R 中指针的解决方法?

r - 如何计算 r 中的二重积分?

r - 在保留索引的同时按向量排序 Dataframe

r - 在构面 (R) 中的所有背景数据上绘制突出显示的线(分类)

r - ggplot2 ggsave : keep embedded fonts in exported . png

r - (函数(el,elname): "plot.title.position" is not a valid theme element name 中出现错误

r - 使用 ggplot2,如何在不扭曲箱线图的情况下设置 y 轴上的刻度线间隔?

R – 如何按最近的时间日期连接两个数据框?

r - 添加形状美学时,ggplot2 找不到对象错误

r - 使用 ggplot2 更改密度图中图例的形状