ggplot上geom_point和geom_smooth的不同颜色比例

时间:2020-05-11 14:12:01

标签: r ggplot2 colors

我正在尝试使用List绘制观测值及其分组的回归线,如下所示:

deriveDecoder[List[X]]

enter image description here 问题是来自ggplot的行都是相同的颜色。我尝试使用ggplot(df, aes(x = cabpol.e, y = pred.vote_share, color = coalshare)) + geom_point() + scale_color_gradient2(midpoint = 50, low="blue", mid="green", high="red") + geom_smooth(aes(x = cabpol.e, y = pred.vote_share, group=coalshare1, fill = coalshare1), se = FALSE, method='lm') + scale_fill_manual(values = c(Junior="blue", Medium="green", Senior="red")) ,以便没有两个不同的色标,然后手动确定与每个组对应的颜色。但相反,所有行都显示为蓝色。如何使每条线具有不同的颜色?

根据要求,这是一组具有相同问题的可复制数据:

geom_smooth

enter image description here

2 个答案:

答案 0 :(得分:1)

我对这个问题的解决方案是创建多个geom_smooth调用,并在每个时间子集所需因子水平的数据。这样,您就可以为geom_smooth的每次调用传递不同的颜色。只要您没有很多因素,此解决方案就不会非常无效。

dff <- data.frame(x=rnorm(100, 0, 1),
                  y=rnorm(100, 1, 2),
                  z=seq(1, 100, 1),
                  g=rep(c("A", "B"), 50))

ggplot(dff, aes(x = x, y = y,
                color = z,
                group = g)) +
    geom_point() +
    scale_color_gradient2(midpoint = 50, low="blue", high="red") + 
    geom_smooth(
     aes(x = x, y =y),
     color = "red",
     method = "lm",
     data = filter(dff, g == "A"),
     se = FALSE
    )  + 
    geom_smooth(
        aes(x = x, y =y),
        color = "blue",
        method = "lm",
        data = filter(dff, g == "B"),
        se = FALSE
    )

enter image description here

答案 1 :(得分:1)

可以通过对geom_line(具有预测值)和geom_point(具有原始数据)函数使用不同的数据帧来绘制x和y变量之间的组趋势。确保在ggplot()函数中确定颜色始终是相同的变量,然后确定geom_line按相同的变量分组。

p2 <- ggplot(NULL, aes(x = cabpol.e, y = vote_share, color = coalshare)) +
  geom_line(data = preds, aes(group = coalshare, color = coalshare), size = 1) +
  geom_point(data = df, aes(x = cabpol.e, y = vote_share)) +
  scale_color_gradient2(name = "Share of Seats\nin Coalition (%)",
      midpoint = 50, low="blue", mid = "green", high="red") +
  xlab("Ideological Differences on State/Market") +
  ylab("Vote Share (%)") +
  ggtitle("Vote Share Won by Coalition Parties in Next Election")

enter image description here

相关问题