【问题标题】:ggplot legend at top but below title?ggplot 图例在顶部但在标题下方?
【发布时间】:2026-02-03 16:15:01
【问题描述】:

有没有办法让 ggplot 将图例放在顶部但在标题下方?

举个例子……

..使用以下代码生成:

carrots<-list(Yield=c(345,226,74,559,288,194), 
              Field=c("A","B","C","D","E","F"), 
              Breed=rep(c("Long","Short"),each=3)) 
carrots<-data.frame(carrots) 

ggplot(carrots,aes(y=Yield,x=Field,fill=Breed)) + 
  geom_bar() + 
  opts(title="Title",
       legend.direction = "horizontal", 
       legend.position = "top") + 
         labs(fill="") 

任何建议将不胜感激?

【问题讨论】:

  • 下个版本已经修复了这个问题。
  • 现在,如果您可以访问 Adob​​e Illustrator,请将绘图保存为 eps,例如ggsave("plot.eps") 然后将图例移到 AI 的顶部。
  • 您可以使用 gridExtra 包微调网格排列的元素并保存不同的元素(不同对象中的绘图、图例、标题)。
  • 这似乎在 ggplot2 的开发版本中得到修复:*.com/questions/9656016/… install.packages("devtools") library(devtools) dev_mode(on=T) install_github("ggplot2") # use dev ggplot2 now # 完成后 do: dev_mode(on=F) #and you are back to have stable ggplot2
  • @EtienneLow-Décarie with grid 我不会在 ggplot2 中使用标题,而是在绘图上方手动添加它(例如使用grid.arrange(plot, main = "title")

标签: r ggplot2


【解决方案1】:

编辑忽略这个。问题不再是问题。 但是代码已经更新,不再抛出错误。

在等待下一个版本的同时,您可以在 ggplot2 中进行微调。例如:

ggplot(carrots, aes(y = Yield, x = Field, fill = Breed)) + 
  geom_bar(stat = "identity") + 
  theme(
     plot.margin = unit(c(2, 1, 1, 1), "cm"), 
     plot.title = element_text(size = 30, face = "bold", colour = "blue", vjust = 7), 
     legend.direction = "horizontal",
     legend.position = c(0.1, 1.05)) + 
   ggtitle("Title") +
  labs(fill = "") 

【讨论】:

  • 您原来的问题已在几天前发布的新版本中得到修复。