将图例移到底部左侧(在 R 中)

Move legend outside the plot to the left at the bottom (in R)

我使用 likert 和 ggplot2 包创建了这张图。 现在,我想将底部的图例向左移动一点,因为图中没有显示最后一部分(强烈同意)。 不幸的是,到目前为止我找不到解决方案。 我怎样才能move/shift左边的图例?

代码:

plot(Likert_Uni_Study_Orientation_OF_V, low.color = "#007CC2", high.color = "#F7971C", neutral.color = "grey", neutral.color.ramp = "white", text.size=9) +
  theme(legend.text=element_text(size=24, margin = margin(r = 30, unit = "pt"))) + 
  theme(legend.direction = "horizontal", legend.position = "bottom") +
  theme(legend.title = element_blank()) +
  ggtitle("Uni Study Orientation – Only Fusha Learners") +
  theme(plot.title = element_text(hjust = 0.5, size =30)) + 
  theme(text = element_text(size = rel(6), color = "black"), axis.text.y = element_text(color = "black")) + 
  theme(axis.text.x = element_text(colour="black", size="30")) + 
  theme(axis.title.x = element_text(vjust=2, size=20, color = "black")) 

感谢您的帮助!

保存到文件时为 width 参数指定一个更高的值。

library(likert)

data(pisaitems)
items29 <- pisaitems[,substr(names(pisaitems), 1,5) == 'ST25Q']
names(items29) <- c("Magazines", "Comic books", "Fiction", 
                    "Non-fiction books", "Newspapers")
l29 <- likert(items29)

plot(l29)

注意图例是如何裁剪的。现在将绘图发送到文件并更改 width 的默认值(对于 png 为 480)。您可能需要尝试几次,直到它看起来恰到好处。

png("l29.png", width=480*1.6)
plot(l29)
dev.off()

另一种选择是将图例放在右侧:

plot(l29, legend.position="right")

第一个答案的补充,对于那些同样是 R 新手并需要进一步解释的人

这些是我的步骤:

  1. I 运行 R 中的代码。第一行包含更改后的宽度(和高度)。在第二行中,我将情节与所有其他特征放在一起。第三行包含 dev.off()。 此代码将绘图以 .png 格式保存在笔记本电脑上的一个文件夹中。
png("Likert_Uni_Study_Orientation_OF_V.png", width=990*2, height=800)
plot("Likert_Uni_Study_Orientation_OF_V, low.color = "#007CC2", high.color = "#F7971C", neutral.color = "grey", neutral.color.ramp = "white", text.size=10) +
  theme(legend.text=element_text(size=28, margin = margin(r = 30, unit = "pt"))) + 
  theme(legend.direction = "horizontal",legend.position = "bottom") +
  theme(legend.title = element_blank()) + 
  ggtitle("Uni Study Orientation – Only Fusha Learners") +
  theme(plot.title = element_text(hjust = 0.5, size =40)) +
  theme(text = element_text(size = rel(7.5), color = "black"), axis.text.y = element_text(color = "black")) +
  theme(axis.text.x = element_text(colour="black", size="30")) +
  theme(axis.title.x = element_text(vjust=2, size=20, color = "black"")
dev.off()
  1. 我必须找出 R 在哪里保存了我的情节。为此,我只使用笔记本电脑上的搜索功能。在我的例子中,它保存在 "My PC" --> "Documents".

你可以使用 cowplot 如此处所述 Center legend in ggplot2 relative to image

(@steph 在评论中给出的link)

当图例太大以至于 ggplot 无法在底部正确显示时,这个也适用。

a= plot(l29)   
library (cowplot)

p1_legend <- get_legend(a+ theme(legend.position = 'right'))
plot_grid(a + theme(legend.position = 'none'), p1_legend,
      nrow = 2, rel_heights = c(1, 1))