我对使用绘制同一图中的点和线有疑问ggplot2
。下面提供了用于生成模拟数据的代码:
library(ggplot2)
set.seed(111)
x = seq(1,10,length=10)
y1 = rnorm(10, 0, 0.1)
y2 = rnorm(10, 5, 0.1)
y3 = rnorm(10, 10, 0.3)
y4 = rnorm(10, 20, 0.4)
label = c(rep("Cat",10), rep("Dog", 10), rep("Owl", 10), rep("Eagle", 10))
dat1 = data.frame(cbind(x, y=y1))
dat2 = data.frame(cbind(x, y=y2))
dat3 = data.frame(cbind(x, y=y3))
dat4 = data.frame(cbind(x, y=y4))
dat = data.frame(rbind(dat1, dat2, dat3, dat4))
dat = cbind(dat, label)
dat
我使用以下代码来生成图:
ggplot(dat, aes(x=x, y=y, colour=label)) +
geom_line(data=dat[dat$label=="Cat", ], aes(x=x, y=y, linetype=label)) +
geom_line(data=dat[dat$label=="Dog", ], aes(x=x, y=y, linetype=label)) +
geom_point(data=dat[dat$label=="Owl", ], aes(x=x, y=y, colour=label)) +
geom_point(data=dat[dat$label=="Eagle", ], aes(x=x, y=y, colour=label)) +
scale_color_manual("Animal",
values = c("Cat" = "darkgreen",
"Dog" = "blue",
"Owl" = "red",
"Eagle" = "cyan")) +
theme_bw() +
scale_linetype_manual(values=c(1,2)) +
scale_alpha_manual(values=c(0.8, 0.8, 0.2, 0.2)) +
scale_size_manual(values=c(1.8, 1.8, 0.6, 0.6)) +
theme(legend.key=element_blank(),
legend.key.width = unit(3, "line"),
legend.key = element_blank())
当前图输出如下所示:
需要更改以下几点以获得我想要的图:
图例位置在情节内部,而不在情节外部
感谢您的帮助/建议。谢谢!
当您使用不同的颜色和线型时,按顺序获取图例的最简单方法是使用function更改原始数据框中的级别顺序factor()
。
dat$label<-factor(dat$label,levels=c("Cat","Dog","Owl","Eagle"))
对于情节我只用一个呼吁geom_point()
,并geom_line()
和设置colour=
,linetype=
并shape=
到label
里面aes()
的ggplot()
。然后使用所需scale_color_manual()
的颜色设置,然后scale_linetype_manual()
为Cat和Dog设置线型1和2,为其他两个级别设置线型0(不可见线)。内部scale_shape_manual()
将“猫和狗”的值设置为NA。在所有手动秤中,使用相同的名称只能得到一个图例。Alpha和规模内的变化geom_point()
和geom_line()
。图例位置通过函数的参数legend.postion=
进行调整theme()
。
ggplot(dat, aes(x=x, y=y, colour=label,linetype=label,shape=label)) +
geom_point(alpha=0.4)+
geom_line(size=2)+
scale_color_manual("Animal",
values = c("Cat" = "darkgreen",
"Dog" = "blue",
"Owl" = "red",
"Eagle" = "cyan")) +
scale_linetype_manual("Animal",values=c(1,2,0,0)) +
scale_shape_manual("Animal",values=c(NA,NA,16,16))+
theme_bw()+
theme(legend.position=c(0.85,0.80))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句