【问题标题】:How to create different colours for the same group between geom_smooth and geom_point?如何在 geom_smooth 和 geom_point 之间为同一组创建不同的颜色?
【发布时间】:2014-02-20 18:50:43
【问题描述】:

我想在同一个组中着色。选择线型也很好。

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

我创建了一些示例数据。

注意:当我尝试在 geom_smooth() 中使用线型时出现错误。

#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:")

【问题讨论】:

  • 不清楚你想达到什么。
  • 我想让给定组的线与点不同。
  • 您可以使用geom_line(aes(x,y,linetype=factor(obs)),data=df) 为给定组添加线,并可以使用scale_linetype_manual 更改线型。我不明白comma_format() 是如何工作的。需要打包吗?
  • 是的,comma_format() 在包库中(刻度)
  • 我相信我可能无法让 R 创建一个我想要的图表。我试图绘制一条与它所基于的数据点组不同颜色的回归线。当我使用 scale_colour_manual() 时,它也适用于基于给定组的所有点/线。即,如果我将第一组颜色设置为蓝色,则回归线和基于第一组的点都是蓝色的。我希望线是黑色,点是蓝色。

标签: r ggplot2


【解决方案1】:

我不确定这是一个特别好的主意,因为您失去了关于哪些点与哪些回归线相关联的视觉线索,但是以下内容对我有用。本质上,我从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% 确定它为什么会这样。

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2021-12-19
    相关资源
    最近更新 更多