将ggplot2图例水平排列并仅占一行

10

我希望我的图表看起来像这样(请注意图例的布局):

enter image description here

我已经尝试使用以下代码实现,但是图例并不完全相同。

  ggplot(mpg, aes(displ, hwy, colour = class)) +
   geom_point() +
   geom_smooth(method = "lm", se = F) +
   theme(legend.position = "bottom", legend.box = "horizontal") +
   scale_color_discrete(NULL) +
   guides(fill = guide_legend(ncol = 1, nrow = 1, byrow = TRUE))
1个回答

19

您将nrow和ncol都设置为1,并且您还设置了错误的指南 - 您应该调整颜色图例,而不是填充。

library(ggplot2)
ggplot(mpg, aes(displ, hwy, colour = class)) +
  geom_point() +
  geom_smooth(method = "lm", se = F) +
  theme(legend.position = "bottom", legend.box = "horizontal") +
  scale_color_discrete(NULL) +
  guides(color = guide_legend(nrow = 1))
#> `geom_smooth()` using formula = 'y ~ x'


(直接翻译为)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接