鉴于下面的示例数据new_mtcars
,对于基于变量geom_path
为new_mtcars$group
手动设置颜色的任何帮助,例如将black
赋予{{1 }}和group1
至red
。
下面,我基于this answer展示我的失败尝试。问题是它根本不应用我要group2
使用的颜色black
和red
。
#准备样品数据
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
在此先感谢您的帮助。
答案 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"))