在ggplot2中手动为geom_path设置颜色,而不会影响绘图的其他元素

时间:2019-03-03 06:03:46

标签: r ggplot2

鉴于下面的示例数据new_mtcars,对于基于变量geom_pathnew_mtcars$group手动设置颜色的任何帮助,例如将black赋予{{1 }}和group1red

下面,我基于this answer展示我的失败尝试。问题是它根本不应用我要group2使用的颜色blackred

#准备样品数据

geom_path

#创建群组

mtmodel <- lm(mpg ~ wt, data = mtcars)
mtcars$Low <- predict(mtmodel, newdata = mtcars, interval = "confidence")[,2]
mtcars$High <- predict(mtmodel, newdata = mtcars, interval = "confidence")[,3]
mtcars$Mean <- predict(mtmodel, newdata = mtcars, interval = "confidence")[,1]
new_mtcars<-tidyr::gather(mtcars, "Variable", "value", Low:Mean)

#为geom_path自动选择颜色绘制绘图

library(tidyverse)
new_mtcars$group <- ifelse(new_mtcars$wt <= 3.5, "group1", "group2")
new_mtcars <- arrange(new_mtcars, wt)

#我尝试根据组的级别手动设置geom_path的颜色

ggplot(new_mtcars, aes(x=wt, y=value, linetype=Variable)) +
  geom_path(size = 0.71, aes(colour = group)) +
  geom_point(aes(colour = cyl)) 

#我当前的输出,该输出不会将所选颜色应用于geo_path

enter image description here

在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这是一种依靠手动定义每种颜色的解决方案。我不知道一种只定义少数几个,剩下的要自动定义的方法。

ggplot(new_mtcars, aes(x=wt, y=value, linetype=Variable)) +
  geom_path(size = 0.71, aes(colour = group)) +
  # In the example, cyl was still numeric, creating an error here,
  #   since group is discrete and ggplot doesn't know how to mix
  #   discrete and continuous variables to the same aesthetic.
  geom_point(aes(colour = as.character(cyl)), shape = 21) +
  scale_color_manual(values = c("4" = "blue", "6" = "green", "8" = "purple", 
                                "group1" = "black", 
                                "group2" = "red"))

enter image description here