首页 > 解决方案 > 无法使用多个 geom_point 和 geom_smooth 指定颜色

问题描述

我有三个数据框(不同大小)。我用这三个 df 创建了一个图表。没关系,但我找不到指定每个图形颜色的正确方法。这是我所做的:

第一种情况,我尝试scale_color_manualaes.

  ggplot()+
  geom_smooth(aes(y=map$MD, x=map$N,color="0"), method = "lm",
              formula = y ~ poly(x, 21),se=F)+
  geom_point(aes(y=whtc[seq(1,1800,by=2),"M"], x=whtc[seq(1,1800,by=2),"N"], color="1"))+
  geom_point(aes(y=etc[seq(1,1800,by=2),"M"], x=etc[seq(1,1800,by=2),"N"], color="2"))+
  coord_cartesian(xlim=c(0,4000),
                ylim = c(0,400))+
  scale_x_continuous(expand = c(0, 0), 
                     breaks = seq(0,5000, by=1000))+
  scale_y_continuous(breaks = seq(0,500, by=100),
                     labels = function(x) format(x, scientific = TRUE,digits = 2))+
  scale_color_manual(values = c("0"="gray", "1"="blue","2"="red"),
                     labels = c("0"="Full load line", "1"="WHTC", "2"="ETC"),
                     name=NULL)

我得到错误:(Error: geom_point requires the following missing aesthetics: x, y ?没有color变量它会产生一个图表)

第二种情况,我试图在aes. 但是在那里,所有的点(geom_point)都是最后一次调用的颜色,即红色。

  ggplot()+
  geom_smooth(aes(y=map$MD, x=map$N),color="gray", method = "lm",
              formula = y ~ poly(x, 21),se=F)+
  geom_point(aes(y=whtc[seq(1,1800,by=5),"M"], x=whtc[seq(1,1800,by=5),"N"]), color="blue")+
  geom_point(aes(y=etc[seq(1,1800,by=5),"M"], x=etc[seq(1,1800,by=5),"N"]), color="red")+
  coord_cartesian(xlim=c(0,4000),
                  ylim = c(0,400))+
  scale_x_continuous(expand = c(0, 0), 
                     breaks = seq(0,5000, by=1000))+
  scale_y_continuous(breaks = seq(0,500, by=100),
                     labels = function(x) format(x, scientific = TRUE,digits = 2))

这是df的负责人:

> dput(head(map))
structure(list(N = c(781.2, 783.3, 788.7, 795.6, 797.4, 807), 
    MD = c(202.6217, 210.3273, 216.0959, 215.3469, 205.2619, 
    212.3705)), row.names = c(NA, 6L), class = "data.frame")
> dput(head(whtc))
structure(list(time = 1:6, speed = c(800, 800, 800, 800, 800, 
800), torque = c(0, 0, 0, 0, 0, 0)), row.names = c(NA, 6L), class = "data.frame")
> dput(head(etc))
structure(list(time = 1:6, N = c(800, 800, 800, 800, 800, 800
), M = c(0, 0, 0, 0, 0, 0)), row.names = c(NA, 6L), class = "data.frame")

我究竟做错了什么 ?

标签: rggplot2

解决方案


推荐阅读