Повернуть легенду боксплота (R, ggplot2) - PullRequest
2 голосов
/ 03 июля 2019

Я использую следующий код.

 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 ]

2 голосов
/ 03 июля 2019

Хорошо, я понял это по предложению @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 голос
/ 03 июля 2019

Вы можете просто положить его сверху

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

Надеюсь, это поможет

...