Обратный порядок легенды при использовании ggplotly () - PullRequest
0 голосов
/ 06 января 2020

Я хотел бы изменить порядок легенды для горизонтальной гистограммы. При добавлении guides(fill = guide_legend(reverse = TRUE)) к ggplot все работает нормально (см. Второй график). Однако после применения ggplotly() легенда снова в порядке по умолчанию.

Как изменить порядок plotly легенды без изменения порядка баров?

library(ggplot2)
library(dplyr)
data(mtcars)

p1 <- mtcars %>%
  count(cyl, am) %>%
  mutate(cyl = factor(cyl), am = factor(am)) %>%
  ggplot(aes(cyl, n, fill = am)) +
  geom_col(position = "dodge") +
  coord_flip()
p1


p2 <- p1 + guides(fill = guide_legend(reverse = TRUE))
p2

plotly::ggplotly(p2)

enter image description here

Ответы [ 3 ]

1 голос
/ 08 января 2020

Когда вы вызываете ggplotly, на самом деле это просто создание списка и вызов функции в этом списке.

Так что, если вы сохраните этот промежуточный шаг, вы можете изменить список напрямую. и как таковой, измените вывод графика.

library(ggplot2)
library(dplyr)
data(mtcars)

p1 <- mtcars %>%
  count(cyl, am) %>%
  mutate(cyl = factor(cyl), am = factor(am)) %>%
  ggplot(aes(cyl, n, fill = am)) +
  geom_col(position = "dodge") +
  coord_flip()

html_plot <- ggplotly(p1)

replace_1 <- html_plot[["x"]][["data"]][[2]]
replace_2 <- html_plot[["x"]][["data"]][[1]]
html_plot[["x"]][["data"]][[1]] <- replace_1
html_plot[["x"]][["data"]][[2]] <- replace_2

html_plot

вывод графика

0 голосов
/ 10 января 2020

В добавление к великолепному ответу @ Za c Garland предлагает решение, которое работает с легендами произвольной длины:

library(ggplot2)
library(dplyr)

reverse_legend_labels <- function(plotly_plot) {
  n_labels <- length(plotly_plot$x$data)
  plotly_plot$x$data[1:n_labels] <- plotly_plot$x$data[n_labels:1]
  plotly_plot
}

p1 <- mtcars %>%
  count(cyl, am) %>%
  mutate(cyl = factor(cyl), am = factor(am)) %>%
  ggplot(aes(cyl, n, fill = am)) +
  geom_col(position = "dodge") +
  coord_flip()

p2 <- mtcars %>%
  count(am, cyl) %>%
  mutate(cyl = factor(cyl), am = factor(am)) %>%
  ggplot(aes(am, n, fill = cyl)) +
  geom_col(position = "dodge") +
  coord_flip()
p1 %>%
  plotly::ggplotly() %>%
  reverse_legend_labels()

enter image description here

p2 %>%
  plotly::ggplotly() %>%
  reverse_legend_labels()

enter image description here

0 голосов
/ 06 января 2020

Простым решением является определение порядка уровней факторной переменной am:

library(ggplot2)
library(dplyr)
data(mtcars)


df <-  mtcars %>%
  count(cyl, am) %>%
  mutate(cyl = factor(cyl), am = factor(as.character(am), levels = c("1", "0"))) 

head(df)


p1 <- df %>%
  ggplot(aes(cyl, n, fill = am)) +
  geom_col(position = "dodge") +
  coord_flip()
p1

enter image description here

plotly::ggplotly(p1)

enter image description here

...