You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot2中将图例标题置于图例项上方?

解决ggplot2图例标题置于图例项上方的问题

要将图例标题放在图例项的上方,只需在theme()中添加两个关键参数:

  • legend.title.position = "top":强制图例标题显示在图例项的上方
  • legend.title.align = 0.5:让标题相对于图例项居中对齐(可选,若偏好左对齐上方可省略此参数)

修改后的完整代码如下:

library(ggplot2)

n <- 200
data <- data.frame(
   subject = sample(LETTERS[1:5], n, TRUE),
   orientation = sample(c("N","S","E","W"), n, TRUE),
   value = runif(n, 0, 100)
)

ggplot(data) + 
   geom_bar(aes(x = subject, y = value, fill = orientation), stat = "identity") +
   theme(
     legend.position = "bottom",
     legend.title.position = "top",
     legend.title.align = 0.5
   )

运行这段代码后,图例标题"orientation"会位于所有图例项的正上方,且保持居中对齐,完全符合需求。

内容的提问来源于stack exchange,提问作者user23145573

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 14:12:02