由于您没有提供任何数据(请在以后提供),这里是一个用于演示解决方案的组合数据集。有(至少)两种方法可以做到这一点:正确的方法和错误的方法。在这个非常简单的情况下,两者都产生相同的结果。
# set up minimum reproducible example
set.seed(1) # for reproducible example
dates <- seq(as.Date("2015-01-01"),as.Date("2015-06-01"), by=1)
df1 <- data.frame(date=dates, NO3=rpois(length(dates),25))
df2 <- data.frame(date=dates, DIS.O2=rnorm(length(dates),50,10))
ggplot
旨在使用“长”格式的数据。这意味着所有 y 值(浓度)都在一个列中,并且有一个单独的列标识相应的类别(在您的情况下为“NO3”或“DIS.O2”)。因此,首先我们根据日期合并两个数据集,然后用于melt(...)
从“宽”(单独列中的类别)转换为“长”格式。然后让我们ggplot
担心图例、颜色等。
library(ggplot2)
library(reshape2) # for melt(...)
# The right way: combine the data-sets, then plot
df.mrg <- merge(df1,df2, by="date", all=TRUE)
gg.df <- melt(df.mrg, id="date", variable.name="Component", value.name="Concentration")
ggplot(gg.df, aes(x=date, y=Concentration, color=Component)) +
geom_point() + labs(x=NULL)

geom_point(...)
执行此操作的“错误”方法是对每一层进行单独调用。在您的特定情况下,这可能更简单,但从长远来看,最好使用其他方法。
# The wrong way: plot two sets of points
ggplot() +
geom_point(data=df1, aes(x=date, y=NO3, color="NO2")) +
geom_point(data=df2, aes(x=date, y=DIS.O2, color="DIS.O2")) +
scale_color_manual(name="Component",values=c("red", "blue")) +
labs(x=NULL, y="Concentration")
