如何以编程方式在ggplot的一系列行中隔离一行

时间:2018-12-26 05:28:28

标签: r ggplot2

我花了整天的时间进行黑客搜索。希望有人能提供帮助。我正在为一个演出季策划一系列下载。我想隔离一个情节并给它加上颜色,而让其他线条保持中性。我之前使用ifelse通过geom_point绘图完成了此操作。我没有尝试过使用geom_line。我觉得解决方案很简单,所以请原谅我。我知道我可以通过手动强制使用已定义颜色矢量的比例尺来做到这一点,但是我想切换变量,并且不想每次都必须手动创建带有颜色值的矢量。

enter image description here

library(plyr)
library(dplyr)
library(ggplot2)

set.seed(407)
getResults <- function(ep_title) {
  days_in_release <- c(1:5)
  downloads <- rbinom(5, 1000, .2)
  cum_downloads <- cumsum(downloads)
  data.frame(days_in_release, downloads, cum_downloads, ep_title)
}

eps <- c("Foo", "Bar", "Gamma", "Ray", "Comet")

season <- lapply(eps, getResults)
season_tidy <- rbind.fill(season)

season_tidy %>% 
  ggplot(aes(days_in_release, cum_downloads, col = ep_title)) + 
  geom_line() +
  scale_color_manual(aes(color = ifelse("Foo" %in% ep_title, "red", "grey")))

3 个答案:

答案 0 :(得分:2)

您可以使用gghighlight

library(gghighlight)
ggplot(season_tidy, aes(days_in_release, cum_downloads, col = ep_title)) + 
  geom_line() +
  gghighlight(ep_title == "Foo")

enter image description here

阅读小插图以获取更多详细信息,vignette("gghighlight")

答案 1 :(得分:1)

你的意思是这样吗?

library(tidyverse)

season_tidy %>%
   ggplot(aes(days_in_release, cum_downloads, col = ep_title)) + 
   geom_line(color = ifelse(season_tidy$ep_title == "Foo", "red", "grey")) 

enter image description here

答案 2 :(得分:1)

尝试一下:

ggplot() + 
  geom_line(data = season_tidy %>% filter(ep_title == "Foo"), 
            aes(days_in_release, cum_downloads, group = ep_title), col="red") +
  geom_line(data = season_tidy %>% filter(ep_title != "Foo"), 
            aes(days_in_release, cum_downloads, group = ep_title), col = "grey")

您也可以执行Ronak建议的操作,但将group arg添加到geom_line

season_tidy %>%
   ggplot(aes(days_in_release, cum_downloads, group = ep_title)) + 
   geom_line(color = ifelse(season_tidy$ep_title == "Foo", "red", "grey"))