r - 如何将图例向上移动到更靠近 ggplot2 中的 x 轴标签

标签 r ggplot2

我正在创建一个函数来创建哑铃图,图例位于底部。但是,它离 x 轴的标题太远了。我想将它稍微向上移动,使其位于 x 轴下方 10 个像素处。

代码如下:

vertical_theme = theme_bw(base_family = "Georgia") +
  theme(
    panel.border = element_rect(color = "black", fill=NA),
    axis.title.x = element_text(hjust=0.5, size = 10, margin=margin(t=10, b=10)),
    axis.text.y = element_text(size=10, margin=margin(r=10), color="black", hjust=0),
    axis.text.x = element_text(size=10, margin=margin(t=10), color="black"),
    axis.title.y = element_blank(),
    legend.title = element_blank(),
    legend.position= "bottom",
    legend.text = element_text(size = 10, margin = margin(r = 10)),
    panel.grid.major.y = element_blank() ,
    panel.grid.minor.y = element_blank(),
    panel.grid.major.x = element_line(size=1), 
    panel.grid.minor.x = element_blank(),
    plot.margin = margin(10, 30, 10, 10, "pt"))

dumbbell = function(df) {
  ggplot(df, aes(pct_responses, Domain)) +
    geom_line(aes(group=Domain)) +
    geom_point(aes(shape=race), size=5, color="#3bbae0" ) +
    vertical_theme + 
    scale_shape_manual(labels = c("Black Students", "White Students"), 
                       values=c(15, 19)) +
    scale_x_continuous(expand = c(0, 0), 
                       limits=c(0,100), 
                       breaks = seq(0, 100, by=20),
                       labels = function(x) paste0(x,"%")) +
    labs(x = "% of Responses") +
    scale_y_discrete(labels = wrap_format(40))
}

dumbbell(df)

这是一个屏幕截图(删除了 y 轴上的标签,因为该数据尚未公开):

enter image description here

我尝试使用 legend.position = c(0.5, 0) 手动调整 legend.position(使用各种不同的数字),但随后图例与“% of Responses”重叠。

最佳答案

使用 theme(legend.margin=margin(-10, 0, 0, 0)) 将图例向上移动。根据需要调整-10

关于r - 如何将图例向上移动到更靠近 ggplot2 中的 x 轴标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60119314/

相关文章:

r - R 中 data.frames 列表的子集

r - 如何防止 marrangeGrob 打开图形设备

r - 如何突出显示两行之间的区域? ggplot

r - 如何获取经纬度范围内的 map ?

r - 如何在 paste0 结果的开头或结尾添加字符?

r - 将模拟泊松分布添加到 ggplot

RSelenium:无法运行示例代码

r - 将 R 中稀疏矩阵的对角线清零的内存有效方法

r - ggplot 中的嵌套面板

r - ggplot : placing facet strips above axis title