我正在尝试将一个图例添加到两个不等长数据的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)")
答案 0 :(得分:0)
我无法复制OP的错误,因此我猜测问题是:“如何使用单独的geom
元素添加图例?”
这里有2个方法:
首先,将单个数据集发送到ggplot并将分组变量添加为自己的列通常是一种好习惯。根据这些分组(即颜色,填充,大小,形状,alpha)设置所需的属性。 ggplot将根据这些分组变量构建一个图例。 (注意:此特定情况不需要单个data.frame,因为您已经对数据进行了子集化以使其变为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)
)))