R ggplot2: geom_area get linetype by group

我们两清 提交于 2021-01-29 07:05:29

问题


I am trying to differentiate the linetype and/or color in stacked geom_area by group. How can I do that? Simply geom_area(linetype = type) or color = type does not work. Only think that works changes the values for both groups: geom_area(color = "white"). How can I modify the color and linetype by group?

My dummy example:

dat <- data.frame(x = c(1:5,1:5),
              y = c(9:5, 10,7,5,3,1),
              type = rep(c("a", "b"), each = 5))

My geom_area:

library(dplyr)

dat %>% 
  ggplot(aes(fill = type,
            x = x,
            y = y)) +
 geom_area(position="stack", 
          stat="identity",
          alpha = 0.5,
          color = "white")

回答1:


Add some extra aesthetics and a geom_line()

dat %>% 
  ggplot(aes(fill = type,
             x = x,
             y = y,
         color = type,
         linetype = type)) +
  geom_area(position="stack", 
            stat="identity",
            alpha = 0.5) +
  geom_line(position = "stack", size = 2)




回答2:


I would suggest this approach. You can work around aes() to define the color using a variable (type) and then you can apply same method for aes() in geom_area() to define linetype. I added a large size so that the difference can be seen:

#Data
dat <- data.frame(x = c(1:5,1:5),
                  y = c(9:5, 10,7,5,3,1),
                  type = rep(c("a", "b"), each = 5))

library(dplyr)
library(ggplot2)
#Plot
dat %>% 
  ggplot(aes(fill = type,
             x = x,
             y = y,color=type)) +
  geom_area(position="stack", 
            stat="identity",
            alpha = 0.5,aes(linetype=type),size=3)

Output:



来源:https://stackoverflow.com/questions/63599077/r-ggplot2-geom-area-get-linetype-by-group

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!