首页 文章

在ggplot2中使用不等长度向量的数据图添加图例

提问于
浏览
1

我试图将一个图例添加到两个不等长数据的geom_point ggplot2中 . 我试图将颜色映射到ggplot()中的美学,但由于数据的长度不同,我得到一个错误 . 有没有办法添加一个图例来解决不同矢量长度的问题?

conc <- c(0.004, 0.003, 0.003, 0.003, 0.004, 0.003, 0.004, 0.008, 0.020)
time <- c(seq(from=1,to=length(conc)))
conc <- c(0.007, 0.012, 0.002, 0.003, 0.003, 0.004, 0.007, 0.003, 0.004, 0.005, 0.004, 0.016)
time <- c(seq(from=1,to=length(conc)))
data1 <- data.frame(time,conc)
data2 <- data.frame(time,conc)

ggplot()+ coord_cartesian(ylim = c(0,0.075))+ 
geom_point(data=data1,aes(time,conc),shape=10,size=.02,color='black')+
geom_step(data=data2,aes(time,conc),size=.1,color='black')+
xlab("Sampling Time (sec)")+
ylab("Concentration (#/cm^3)")

1 回答

  • 0

    我无法复制OP 's error, so I'猜测问题是:“如何使用单独的 geom 元素添加图例?”

    这里有两种方法:

    • 基本:一个数据集,来自aes的传奇()

    • 高级:customized legend keys(几乎直接从链接的答案中复制) .

    首先,它对于这个特定情况是必要的,因为您已经将数据子集化为不同的 geoms . )

    #Example data
    conc <- c(0.004, 0.003, 0.003, 0.003, 0.004, 0.003, 0.004, 0.008, 0.020)
    time <- c(seq(from=1,to=length(conc)))
    data1 <- data.frame(time,conc)    
    conc <- c(0.007, 0.012, 0.002, 0.003, 0.003, 0.004, 0.007, 0.003, 0.004,
              0.005, 0.004, 0.016)
    time <- c(seq(from=1,to=length(conc)))
    data2 <- data.frame(time,conc)
    
    #Create grouping variables
    data1$category <- "myPoint"
    data2$category <- "myStep"
    data3 <- rbind(data1, data2)
    

    基本方法:

    #Graph the combined data, setting the overall aes()
    #but subset the data for the different visual elements (points and steps)
    ggplot(data3, aes(time, conc, colour=category))+ coord_cartesian(ylim = c(0,0.075))+ 
      geom_point(data=data3[data3$category == "myPoint",], shape=10,size=2)+
      geom_step( data=data3[data3$category == "myStep", ], size=1)+
      xlab("Sampling Time (sec)")+
      ylab("Concentration (#/cm^3)") + 
      ggtitle("Basic")
    

    高级方法:

    #Specify a custom colour in each variable's aesthetics
    #Hack the legend: color = guide_legend(override.aes = list(...))
    ggplot()+ coord_cartesian(ylim = c(0,0.075))+ 
      geom_point(data=data1,aes(time,conc, color='point'),shape=10,size=2)+
      geom_step(data=data2,aes(time,conc, color='step'),size=1)+
      xlab("Sampling Time (sec)")+
      ylab("Concentration (#/cm^3)") +
      ggtitle("Advanced") +
      scale_colour_manual(name = "legend", 
                          values = c("point" = "black", "step" = "black")) +
      guides(color=guide_legend(override.aes=list(
                   shape=c(10, NA),
                   linetype=c(0,1) 
                    )))
    

    same legend, different geoms

    override.aes point and line different geoms

相关问题