ggplot:(手动)在引用不同的data.frames时创建图例
好的,让我们获取一些样本数据ggplot:(手动)在引用不同的data.frames时创建图例,r,ggplot2,legend,R,Ggplot2,Legend,好的,让我们获取一些样本数据 A <- sample(1:100, 25) B <- sample(1:25, 25) df.1 <- data.frame(A,B) C <- sample(1:80, 15) D <- sample(1:15, 15) df.2 <- data.frame(C,D) 因此,我们创建并修改了标题、轴等 但是我想创建一个图例,显示df.1和df.2的geom_smooth()函数中的线型。它应该在图表的右上角 (因此对于d
A <- sample(1:100, 25)
B <- sample(1:25, 25)
df.1 <- data.frame(A,B)
C <- sample(1:80, 15)
D <- sample(1:15, 15)
df.2 <- data.frame(C,D)
因此,我们创建并修改了标题、轴等
但是我想创建一个图例,显示df.1
和df.2
的geom_smooth()
函数中的线型。它应该在图表的右上角
(因此对于df.1
我们需要一条实线,而df.2
需要一条虚线)
本示例将引导您完成一个示例,但数据来自同一数据集中
#combine and create x and y (as mappings follow
#same pattern)
df.1$group <- "df.1"
df.1$x <- df.1$A
df.1$y <- df.1$B
df.2$group <- "df.2"
df.2$x <- df.2$C
df.2$y <- df.2$D
library(plyr) #for rbind.fill
df.all <- rbind.fill(df.1,df.2)
plot3 <- ggplot(df.all, aes(x=x,y=y,group=group)) +
geom_point(color='black', cex=1, pch=16 ) +
geom_smooth(aes(linetype=group),method="lm", size=1,
se=FALSE, colour="black") +
scale_y_continuous("Y scale") +
ggtitle("Plot") +
theme_bw()+
theme(plot.title = element_text(face="bold", size=20),
axis.title.x = element_text(vjust=-0.25),
axis.title.y = element_text(vjust=1),
axis.title = element_text(face="bold", size=15)
) +
#add custom linetypes (not necessary now, as default mapping to 1 and 2)
plot3 + scale_linetype_manual(values=c("df.1"=1,"df.2"=2))
#组合并创建x和y(如下映射所示
#(相同模式)
df.1$group我很好奇,为什么你需要这两个数据帧?首先合并数据然后按源分组不是更容易吗?假设它们具有不同的数据长度和不同的变量名称。但是,如果您可以合并到一个dataframeDone,很高兴看到一个解决方案。事后看来,merge是个错误的词。我的意思是合并。谢谢,所以当你有变量长度的data.frames时,最好合并它们,然后绘图。感谢您的建议,不一定,但是当您对每个数据帧执行基本相同的操作时(就像您在这里所做的),最好与一列组合,以指示度量值属于哪个组。然后,您可以按组指示器分组并分配美学(使用自动生成图例的aes(…)
)。
#combine and create x and y (as mappings follow
#same pattern)
df.1$group <- "df.1"
df.1$x <- df.1$A
df.1$y <- df.1$B
df.2$group <- "df.2"
df.2$x <- df.2$C
df.2$y <- df.2$D
library(plyr) #for rbind.fill
df.all <- rbind.fill(df.1,df.2)
plot3 <- ggplot(df.all, aes(x=x,y=y,group=group)) +
geom_point(color='black', cex=1, pch=16 ) +
geom_smooth(aes(linetype=group),method="lm", size=1,
se=FALSE, colour="black") +
scale_y_continuous("Y scale") +
ggtitle("Plot") +
theme_bw()+
theme(plot.title = element_text(face="bold", size=20),
axis.title.x = element_text(vjust=-0.25),
axis.title.y = element_text(vjust=1),
axis.title = element_text(face="bold", size=15)
) +
#add custom linetypes (not necessary now, as default mapping to 1 and 2)
plot3 + scale_linetype_manual(values=c("df.1"=1,"df.2"=2))