Подтвердить что ты не робот

Размещение легенды, ggplot, относительно области построения графика

Проблема здесь немного очевидна, я думаю. Я бы хотел, чтобы легенда была помещена (заблокирована) в верхнем левом углу области печати. Использование c (0,1,0.13) и т.д. Не является вариантом по ряду причин.

Есть ли способ изменить опорную точку для координат, чтобы они были относительно области построения графика?

mtcars$cyl <- factor(mtcars$cyl, labels=c("four","six","eight"))
ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + 
opts(legend.position = c(0, 1), title="Legend placement makes me sad")

enter image description here

Приветствия

4b9b3361

Ответ 1

Размещение руководства основано на области графика (т.е. области, заполненной серым цветом) по умолчанию, но выравнивание по центру. Поэтому вам нужно установить правостороннее выравнивание:

ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + 
  opts(legend.position = c(0, 1), 
       legend.justification = c(0, 1), 
       legend.background = theme_rect(colour = NA, fill = "white"),
       title="Legend placement makes me happy")

enter image description here

Если вы хотите разместить руководство по всей области устройства, вы можете настроить выходной файл:

p <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + 
  opts(legend.position = c(0, 1), 
       legend.justification = c(0, 1), 
       legend.background = theme_rect(colour = "black"),
       title="Legend placement makes me happy")

gt <- ggplot_gtable(ggplot_build(p))
nr <- max(gt$layout$b)
nc <- max(gt$layout$r)
gb <- which(gt$layout$name == "guide-box")
gt$layout[gb, 1:4] <- c(1, 1, nr, nc)
grid.newpage()
grid.draw(gt)

enter image description here

Ответ 2

Просто, чтобы развернуть на кохском ответе, так что он станет более полным для следующего человека, чтобы наткнуться на него.

mtcars$cyl <- factor(mtcars$cyl, labels=c("four","six","eight"))
library(gridExtra)

a <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + 
opts(legend.justification = c(0, 1), legend.position = c(0, 1), title="Legend is top left")
b <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + 
opts(legend.justification = c(1, 0), legend.position = c(1, 0), title="Legend is bottom right")
c <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + 
opts(legend.justification = c(0, 0), legend.position = c(0, 0), title="Legend is bottom left")
d <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + 
opts(legend.justification = c(1, 1), legend.position = c(1, 1), title="Legend is top right")

grid.arrange(a,b,c,d)

enter image description here

Ответ 3

Я искал аналогичный ответ. Но обнаружил, что функция opts больше не является частью пакета ggplot2. После поиска еще некоторое время я обнаружил, что можно использовать theme для выполнения аналогичной функции, как выбор. Поэтому отредактируйте этот поток, чтобы минимизировать время.

Ниже приведен аналогичный код, написанный nzcoops.

mtcars$cyl <- factor(mtcars$cyl, labels=c("four","six","eight"))
library(gridExtra)

a <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + labs(title = "Legend is top left") + 
theme(legend.justification = c(0, 1), legend.position = c(0, 1))

b <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + labs(title = "Legend is bottom right") +
theme(legend.justification = c(1, 0), legend.position = c(1, 0))

c <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + labs(title = "Legend is bottom left") +
theme(legend.justification = c(0, 0), legend.position = c(0, 0))

d <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + labs(title = "Legend is top right") +
theme(legend.justification = c(1, 1), legend.position = c(1, 1))

grid.arrange(a,b,c,d)

Этот код даст точно такой же сюжет.

Ответ 4

Чтобы расширить расширенные ответы выше, если вы хотите добавить отступы между легендой и пределами поля, используйте legend.box.margin:

# Positions legend at the bottom right, with 50 padding
# between the legend and the outside of the graph.
theme(legend.justification = c(1, 0), 
    legend.position = c(1, 0),
    legend.box.margin=margin(c(50,50,50,50)))

Это работает с последней версией ggplot2, которая является v2.2.1 на момент написания.