ggplot优先考虑行重叠

时间:2019-05-17 13:58:17

标签: r ggplot2

library(tidyverse)
mtcars %>% 
  mutate(ID = row_number()) %>% 
  select(ID, vs, am, gear, carb) %>% 
  gather(key, value, 2:5) %>% 
  mutate(violation = c(rep(FALSE, 96), rep(TRUE, 32))) %>% 
  ggplot(aes(ID, value, group = key, color = violation)) + 
  scale_color_manual(values = c("grey", "red")) + 
  geom_line() + 
  theme_classic()

在下面的图像中,红色的'violation'线被细分了。我认为这是因为ggplot是按顺序绘制线,而灰线之一是在红线之后以相同的坐标绘制的。如何阻止灰色线条与红色重叠?

正如其他stackoverflow问题中所提到的,我将添加一条单独的行,如下所示:

geom_line(df %>% filter(violation == TRUE), aes(color = "red")) +

但是当我的数据帧中没有违规时,这会导致问题。我每月进行分析,有些月份包含违规情况,有些月份则没有。如果我在上面添加此单行,则在没有违反的月份中会出现错误“长度必须大于0” ,因此这种单线方法可能行不通。

enter image description here

1 个答案:

答案 0 :(得分:3)

您可能会使用以下代码(与代码相比,只有2个小的更改)

library(tidyverse)
mtcars %>% 
  mutate(ID = row_number()) %>% 
  select(ID, vs, am, gear, carb) %>% 
  gather(key, value, 2:5) %>% 
  mutate(violation = c(rep(FALSE, 96), rep(TRUE, 32))) %>% 
  ggplot(aes(ID, value, group = key, color = violation)) + 
  scale_color_manual(values = c("grey", "red")) + 
  geom_line(alpha = .5, size= 1.2) + ### changes in transparancy and thickness ###
  theme_classic()

产生此情节: enter image description here

“ H 1”的建议是改变线图顺序的另一种方法:

mtcars %>% 
  mutate(ID = row_number()) %>% 
  select(ID, vs, am, gear, carb) %>% 
  gather(key, value, 2:5) %>% 
  mutate(violation = c(rep(FALSE, 96), rep(TRUE, 32))) %>% 
  ggplot(aes(ID, value, group = key, color = violation)) + 
  scale_color_manual(values = c("grey", "red")) + 
  geom_line(aes(group = rev(key))) + ### changes sequence of plotting of the lines ###
  theme_classic()

这将产生以下情节:

enter image description here