gpt4 book ai didi

r - ggplot2 中两个图例的共同边界

转载 作者:行者123 更新时间:2023-12-02 01:32:14 30 4
gpt4 key购买 nike

我正在生成一个简单的图表:

data(iris); require(ggthemes)
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) +
geom_point(aes(shape=Species, colour=Petal.Width)) +
scale_colour_gradient() +
theme_gdocs() +
labs(shape="Species label", colour="Petal width label")

Initial chart

我想在这两个图例之间画一条共同的边界:

with common border

显然,代码 theme(legend.background = element_rect(colour = 'black')) 将生成两个边框,每个边框用于每个图例元素。

最佳答案

编辑
从 2.2.0 版开始,ggplot 允许为每个单独的图例 (legend.background) 和组合图例 (legend.box.背景)。将 legend.box.background 设置为所需的颜色、填充、大小等。同时将 legend.background 设置为 element_blank()

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) +
geom_point(aes(shape=Species, colour=Petal.Width)) +
scale_colour_gradient() +
theme_gdocs() +
labs(shape="Species label", colour="Petal width label") +

theme(legend.background = element_blank(),
legend.box.background = element_rect(size = 2))

您可能需要深入研究 ggplot grob 的结构;像这样:

小修改:更新到 ggplot2 2.0.0(和 ggthemes 3.0.0)

# Load packages and data
library(ggplot2)
library(gtable)
library(grid)

data(iris)

# Small problem with theme_gdocs drawing a border around each legend.
# Fixed in the github development version
# library(devtools)
# install_github("jrnold/ggthemes")
library(ggthemes)


p <- ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) +
geom_point(aes(shape=Species, colour=Petal.Width)) +
scale_colour_gradient() +
theme_gdocs() +
labs(shape="Species label", colour="Petal width label")

# Get the ggplot grob
gt = ggplotGrob(p)

# Get the combined legend
leg = gtable_filter(gt, "guide-box")

# Get the individual legends - to get their widths and heights
leg1 = leg$grobs[[1]]$grobs[[1]]
leg2 = leg$grobs[[1]]$grobs[[2]]

# Calculate widths and heights for border (Note: some margin widths are dropped from widths)
rectHeight = sum(leg1$heights + leg2$heights)
rectWidth = sum(unit.pmax(leg1$widths[3:5], leg2$widths[3:5]))

# Create border with widths and heights
rect <- rectGrob( width = rectWidth, height = rectHeight,
gp = gpar(col = "black", fill = NA, lwd = 5), name = "gRect")

# Create combined legend - i.e., legend plus border
leg <- grobTree(leg, rect)

# Insert combined legend back into ggplot grob
gt$grobs[gt$layout$name == "guide-box"][[1]] <- leg

# Draw it
grid.newpage()
grid.draw(gt)

enter image description here

关于r - ggplot2 中两个图例的共同边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33482860/

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