我正在创建一个函数来创建哑铃图,图例位于底部。但是,它离 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 轴上的标签,因为该数据尚未公开):
我尝试使用 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/