Invert factors in only 1 bar in ggplot2

Asked

Viewed 175 times

3

Does anyone have any idea how the order of the factors in only 1 bar in ggplot2? Reordering the data no longer works :(

In case I would like to reverse the first bar, so that the green was up and the red was down.

Exemplo

library(ggplot2)

dados <- expand.grid(a = letters[1:5], b = letters[1:2])
dados$a <- paste(dados$a)
dados$b <- paste(dados$b)
dados$val <- rnorm(10, 5, 1)
ggplot(aes(x = a, y = val, fill = b), data = dados) + geom_bar(stat = 'identity')

dados2 <- rbind(tail(dados, -1), head(dados, 1))
ggplot(aes(x = a, y = val, fill = b), data = dados2) + geom_bar(stat = 'identity') # Funcionava nas versões anteriores :\
  • Only on the first bar?

  • @Daniel yes, only on the first bar

  • 1

    It will probably have to be a separate geom_bar, which comes from a separate dataset

1 answer

5

Gambiarra, but it works:

dados2$c <- ifelse(dados2$a == "a", dados2$b, NA)
dados2$d <- ifelse(dados2$a == "a", dados2$val, NA)
dados2$val[dados2$a == "a"] <- NA
ggplot(aes(x = a, y = d, fill = c), data = dados2) + 
  geom_bar(stat = 'identity', position = position_stack(reverse = TRUE)) +
  geom_bar(aes(x = a, y= val, fill = b), stat= "identity")

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.