首页 文章

如何在geom_smooth和geom_point之间为同一组创建不同的颜色?

提问于
浏览
0

我想要在同一组中使用颜色 . 选择线型也很不错 .

对于给定的线型,我希望geom_point中的颜色与使用geom_point绘制的点的颜色略有不同 . 我想让给定组的线与点不同 . 我该怎么做呢?

我创建了一些示例数据 .

注意:当我尝试在geom_smooth()中使用linetype时出现错误 .

#test data
obs=rep(1:3, each=30)
length(obs)
set.seed(50)
x=sample(seq(from = 20, to = 50, by = 5), size = 90, replace = TRUE)
y=sample(seq(from = 200, to = 500, by = 5), size = 90, replace = TRUE)

df = data.frame(obs,x,y)
ggplot(df, aes(x, y, color = factor(obs)))+
geom_point()+
theme(legend.position="bottom")+
scale_x_continuous(breaks = seq(0, 50, by = 4),expand = c(0, 0), labels = comma_format())+
scale_y_continuous(breaks = seq(0, 500, by = 10),limits = c(0, 500),expand = c(0, 0), labels = comma_format())+
geom_smooth(aes(group=obs), method="lm")+
scale_colour_manual(values = c("wheat3", "slategray1","dimgray"),name = "Average Density Band:")

1 回答

  • 0

    我不确定这是一个特别好的主意,因为你失去了关于哪些点与回归线相关的视觉线索,但是下面的内容对我有用 . 基本上,我从 ggplot() 调用中获取了颜色美学,并将其单独传递给 geom_point()geom_smooth() .

    library(ggplot2)
    library(scales)
    #test data
    obs=rep(1:3, each=30)
    length(obs)
    set.seed(50)
    x=sample(seq(from = 20, to = 50, by = 5), size = 90, replace = TRUE)
    y=sample(seq(from = 200, to = 500, by = 5), size = 90, replace = TRUE)
    
    df = data.frame(obs,x,y)
    ggplot(df, aes(x, y))+
    geom_point(color = factor(obs))+
    theme(legend.position="bottom")+
    scale_x_continuous(breaks = seq(0, 50, by = 4),expand = c(0, 0), labels = comma_format())+
    scale_y_continuous(breaks = seq(0, 500, by = 10),limits = c(0, 500),expand = c(0, 0), labels = comma_format())+
    geom_smooth(aes(group=obs, color = factor(obs)), method="lm")+
    scale_colour_manual(values = c("orange", "yellow","blue"),name = "Average Density Band:")
    

    我改变了你的线条颜色,因为我用我的视力无法看到它们 . 我怀疑这并不意味着像这样工作,坦率地说,我不能100%确定为什么会这样 .

相关问题