使用 geom_col() 时如何对 y 结果进行排序?

How can I sort my y result when using geom_col()?

我有两个地块:

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))

第一个看起来像这样:

第二个看起来像这样:

我希望他们的 y 结果都按升序排列。我该怎么做?

Ggplot 使用因子顺序来决定列的顺序。 您需要重新排序该因素。您可以根据另一个(数字)变量以升序或降序对因子(在本例中为“流”)重新排序。你没有提供整个数据集,所以我做了一些数据来说明:

´´´´

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")

顺序不是升序。但是,如果您将 mutate 与 fct_reorder 结合使用,并根据“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")

您可以使用 forcats 包中的 fct_reorder()ggplot() 命令中重新排序因子。

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()

reprex package (v2.0.1)

于 2021-11-18 创建

要颠倒顺序,运行

ggplot(df, aes(x = forcats::fct_reorder(streaming, desc(score)), y = score)) +
         geom_col()