旋转箱线图例(R,ggplot2)

时间:2019-07-03 10:10:09

标签: r ggplot2 legend

我正在使用以下代码。

 library(ggplot2)
 mtcars$carb <- as.factor(mtcars$carb)
 mtcars$am <- as.factor(mtcars$am)
 mtcars <- mtcars[!(mtcars$carb==6 | mtcars$carb==8),]
 ggplot(mtcars) + 
    geom_boxplot(aes(x = carb, y = mpg, fill = am), 
                 position = position_dodge(0.9)) +
 guides(fill = guide_legend(direction = "horizontal"))

结果是:

enter image description here

我想旋转图例以获得所需的结果:

enter image description here

有人可以帮忙吗?谢谢。

2 个答案:

答案 0 :(得分:2)

好的,我根据@LFischer的建议弄清楚了。也许有一种更简单的方法,但是经过反复试验,这为我做到了:

 library(ggplot2)
 mtcars$carb <- as.factor(mtcars$carb)
 mtcars$am <- as.factor(mtcars$am)
 mtcars <- mtcars[!(mtcars$carb==6 | mtcars$carb==8),]
 ggplot(mtcars) + 
    geom_boxplot(aes(x = carb, y = mpg, fill = am), 
                 position = position_dodge(0.9)) +
 guides(fill = guide_legend(reverse = TRUE, direction = "vertical", label.position = "top", label.theme = element_text(angle = 90, vjust = 0.5), title.position = "bottom", title.theme = element_text(angle = 90)))

答案 1 :(得分:1)

您可以将其放在顶部

library(ggplot2)
 mtcars$carb <- as.factor(mtcars$carb)
 mtcars$am <- as.factor(mtcars$am)
 mtcars <- mtcars[!(mtcars$carb==6 | mtcars$carb==8),]
 ggplot(mtcars) + 
    geom_boxplot(aes(x = carb, y = mpg, fill = am), 
                 position = position_dodge(0.9)) +
theme(legend.position = "top")

example_img

或者您可以使其垂直

library(ggplot2)
mtcars$carb <- as.factor(mtcars$carb)
mtcars$am <- as.factor(mtcars$am)
mtcars <- mtcars[!(mtcars$carb==6 | mtcars$carb==8),]
ggplot(mtcars) + 
  geom_boxplot(aes(x = carb, y = mpg, fill = am), 
               position = position_dodge(0.9)) +
  theme(legend.direction = "vertical")

example_img_2

希望有帮助