并排在ggplot2中的水平图例

gja*_*bel 18 r ggplot2

我想让我的ggplot传说并排出现在情节下面,变量名称在符号上方,就像它们在这篇博文(第二个情节)中一样.该opts功能现已不存在,theme似乎没有复制其行为......

library("ggplot2")
ggplot(diamonds, aes(x = carat, y=price, shape = cut, group=interaction(cut, color), color=color)) +
geom_point() +
#opts(legend.direction = "horizontal", legend.position = "bottom")
#potential options, not all seem have an effect...
theme(legend.direction = "horizontal") +
theme(legend.position = "bottom") +
theme(legend.box = "vertical") +
theme(legend.title.align = 0)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

...使用我的MS绘画技巧来说明所需的情节.

And*_*rie 21

你需要指定 theme(legend.box = "horizontal")

试试这个:

library("ggplot2")
ggplot(diamonds, aes(x = carat, y=price, shape = cut, group=interaction(cut, color), color=color)) +
  geom_point() +
  theme(legend.direction = "horizontal", 
        legend.position = "bottom",
        legend.box = "horizontal"
        )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 知道如何在符号上方获得剪切和颜色标题吗? (2认同)
  • @MonaJalal 尝试在引号中使用垂直:`“垂直”` (2认同)

gja*_*bel 13

根据之前的建议legend.box = "horizontal",我发现您可以title.position = "top"scale_功能指南中使用顶部的图例标题.必须为构成图例的每个变量定义这些,否则标题将在左侧.

ggplot(data = diamonds, 
       mapping = aes(x = carat, y = price, shape = cut,
                     group=interaction(cut, color), color=color)) +
  geom_point() +
  theme(legend.box = "horizontal",
        legend.position="bottom") +
  scale_shape(guide = guide_legend(title.position = "top")) +
  scale_colour_discrete(guide = guide_legend(title.position = "top", nrow = 1))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

您可以将标题转移到中心,正如我在问题中建议的那样title.hjust = 0.5.但是,经过检查,这样做可能会使读者混淆哪些颜色/点指的是哪个变量.


小智 5

@gjbel - 我认为要将图例标题放在符号上方,您需要将图例方向从水平更改为垂直,或者完全删除图例方向,因为默认为垂直:

library("ggplot2")
ggplot(diamonds, aes(x = carat, y=price, shape = cut, group=interaction(cut, color), color=color)) +
  geom_point() +
  theme(legend.direction = "vertical", 
        legend.position = "bottom",
        legend.box = "horizontal"
        )
Run Code Online (Sandbox Code Playgroud)

或者

library("ggplot2")
    ggplot(diamonds, aes(x = carat, y=price, shape = cut, group=interaction(cut, color), color=color)) +
      geom_point() +
      theme(legend.position = "bottom",
            legend.box = "horizontal"
            )
Run Code Online (Sandbox Code Playgroud)