要将图例位置设置在图plot内部,需要使用ggplot2中的theme函数,并设置legend.position参数为'none',再用legend.box参数设置图例框的位置和大小。

下面是一个例子:

library(ggplot2)

# 创建一个数据集
data <- data.frame(x = c(1, 2, 3), y = c(2, 4, 6), group = c('A', 'B', 'C'))

# 绘制散点图
p <- ggplot(data, aes(x, y, color = group)) +
  geom_point(size = 4) +
  theme(legend.position = 'none') +
  guides(color = guide_legend(
    title = 'Group',
    title.position = 'top',
    label.position = 'left',
    label.theme = element_text(size = 12),
    ncol = 3,
    byrow = TRUE,
    keywidth = unit(2, 'cm'),
    keyheight = unit(0.5, 'cm'),
    label.padding = unit(0.5, 'cm'),
    label.spacing = unit(0.5, 'cm'),
    label.hjust = 0
  )) +
  theme(plot.margin = unit(c(1, 1, 1, 1), 'cm')) +
  theme(legend.box = 'horizontal',
        legend.box.just = 'center',
        legend.box.background = element_rect(fill = 'white', color = 'gray', size = 0.5),
        legend.box.margin = unit(0.5, 'cm'))

# 输出图形
p

这个例子中,我们使用了guides函数来自定义图例的样式,并设置了legend.box参数来控制图例框的位置和大小。最终的图像如下所示:

image

R语言ggplot2绘图:将图例放置在绘图区域内

原文地址: https://www.cveoy.top/t/topic/nCQI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录