将ggplot2图例设为水平和一行

3 r 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(fill = guide_legend(ncol = 1, nrow = 1, byrow = TRUE))
Run Code Online (Sandbox Code Playgroud)

ala*_*han 7

您将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))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述