我正在使用以下代码。
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"))
结果是:
我想旋转图例以获得所需的结果:
有人可以帮忙吗?谢谢。
答案 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")
或者您可以使其垂直
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")
希望有帮助