gpt4 book ai didi

r - 分别绘制从 grob 中提取的图例

转载 作者:行者123 更新时间:2023-12-01 12:43:41 24 4
gpt4 key购买 nike

我有一个 ggplot 对象:

ggplot(plot1,aes(x = c, y = value, colour = variable, linetype = variable,size = variable)) + 
geom_line() +
scale_x_continuous(breaks=seq(1,10,1)) +
#scale_y_continuous(breaks=seq(0,1, 0.1))+
scale_colour_manual(values=c("blue3","red3")) +
scale_linetype_manual(values = c(3,1)) +
scale_size_manual(values = c(0.6,0.3)) +
xlab("b") +
ylab("a") +
theme_bw() +
theme(axis.text=element_text(size=5),
axis.title=element_text(size=5),
axis.line = element_line(size=0.25),
axis.ticks=element_line(size=0.25),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
legend.position="right" ,
legend.direction="vertical",
legend.title=element_blank(),
legend.text=element_text(size=8),
legend.background=element_blank(),
legend.key=element_blank())

我想单独绘制相应的图例。

是否有可能以某种方式提取它?

我尝试使用这个函数来保存图例,但它只返回空 quartz 窗口,但没有图例。

g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}

来源:https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs

最佳答案

使用情节代码的简化版本:

# base plot
p1 <- ggplot(plot1,aes(x=c, y=value, colour=variable, linetype=variable, size=variable)) +
geom_line()

# extract the different legends
leg1 <- p1 + guides(linetype=FALSE, size=FALSE)
leg2 <- p1 + guides(colour=FALSE, size=FALSE)
leg3 <- p1 + guides(colour=FALSE, linetype=FALSE)
legend.colour <- gtable_filter(ggplot_gtable(ggplot_build(leg1)), "guide-box")
legend.linetype <- gtable_filter(ggplot_gtable(ggplot_build(leg2)), "guide-box")
legend.size <- gtable_filter(ggplot_gtable(ggplot_build(leg3)), "guide-box")

leg1Grob <- grobTree(legend.colour)
leg2Grob <- grobTree(legend.linetype)
leg3Grob <- grobTree(legend.size)

p2 <- p1 + guides(colour=FALSE, linetype=FALSE, size=FALSE)

# final plot were you can place the legends were you want them
finplot <- p2 +
annotation_custom(grob = leg1Grob, xmin = ??, xmax = ??, ymin = ??, ymax = ??) +
annotation_custom(grob = leg2Grob, xmin = ??, xmax = ??, ymin = ??, ymax = ??) +
annotation_custom(grob = leg3Grob, xmin = ??, xmax = ??, ymin = ??, ymax = ??)

如果您想放置图例,请将 ?? 替换为绘图中的坐标。

当你想单独绘制图例时,用 geom_blank 制作一个空白图

关于r - 分别绘制从 grob 中提取的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21989182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com