Reputation: 123
I have two plots:
1.
ggplot() + geom_col(data = descritivasseries,
aes(x = streaming, y = media_IMDB),
fill = "seagreen1") +
coord_cartesian(ylim = c(6.85, 7.20)) +
labs(title = "Avaliação das Séries",
x = "", y = "Média das Notas IMDb")
ggplot() + geom_col(data = descritivasfilmes,
aes(x = streaming, y = media_IMDB),
fill = "deepskyblue") +
labs(title = "Avaliação dos Filmes", x = "", y = "Média das Notas IMDb") +
coord_cartesian(ylim = c(5.85, 6.6))
The first one looks like this:
And the second one looks like this:
I would like both of their y results to be organized in ascending order. How would I do that?
Upvotes: 3
Views: 4343
Reputation: 136
You can reorder factors within a ggplot()
command using fct_reorder()
from the forcats package.
library(ggplot2)
library(forcats)
df <- data.frame(
streaming = c("Disney", "Hulu", "Netflix", "Prime Video"),
score = c(4, 2, 3, 1)
)
# no forcats::fct_reorder()
ggplot(df, aes(x = streaming, y = score)) +
geom_col()
# with forcats::fct_reorder()
ggplot(df, aes(x = forcats::fct_reorder(streaming, score), y = score)) +
geom_col()
Created on 2021-11-18 by the reprex package (v2.0.1)
To reverse the order, run
ggplot(df, aes(x = forcats::fct_reorder(streaming, desc(score)), y = score)) +
geom_col()
Upvotes: 4
Reputation: 136
Ggplot uses factor order to decide the order of the columns. You need to reorder the factor. You can reorder the factor (in this case "streaming") according to another (numeric) variable in ascending or descending order. You didn't provide the whole data set, so to illustrate I made some data :
´´´´
library (ggplot2)
library(dplyr)
library(forcats)
descritivasseries <- tibble(streaming = c("Hulu", "Disney", "Netflix", "Prime Video"),
media_IMDB = c(15, 13, 18, 10))
ggplot() + geom_col(data = descritivasseries,
aes(x = streaming, y = media_IMDB),
fill = "seagreen1") +
labs(title = "Avaliação das Séries",
x = "", y = "Média das Notas IMDb")
The order is not ascending. However if you use mutate in conjunction with fct_reorder, and reorder "streaming" according to "media_IMDB" :
descritivasseries %>% mutate(streaming = fct_reorder(streaming, media_IMDB, .desc=FALSE)) %>%
ggplot() + geom_col(aes(x = streaming, y = media_IMDB),
fill = "seagreen1") +
labs(title = "Avaliação das Séries",
x = "", y = "Média das Notas IMDb")
Upvotes: 2