需要重新排序配对条形图

问题描述 投票:0回答:1

如何更改配对条的顺序?

我希望每对阿拉斯加(浅蓝色)都高于 AM 西部(深蓝色)。

ggplot(data=Overview_All_flights_by_Airline_and_Destination1, 
       aes(x= Percent_Ontime, y=reorder(Destination, +Percent_Ontime), 
            fill=Airline)) +
  geom_bar(stat="identity", color="black",position=position_dodge()) +
  geom_text(aes(label=Percent_Ontime), vjust=-0.3, 
                position = position_dodge(0.9), size=3.5) +
  scale_fill_brewer(palette="Paired") +
  theme_minimal()  

r ggplot2
1个回答
0
投票

让事情变得困难的是 y 轴和 x 轴被翻转了。 一种选择是将

airline
定义为一个因子并设置
levels
的顺序。 使用
forcats
库允许,您可以将翻转轴更改的内容反转回来。使用
forcats::fct_rev
y 轴和填充需要反转。 图例项的顺序也可以采用
rev
.

我做了一个虚拟的DF,和你自己的DF很接近

library(ggplot2)
library(forcats)
set.seed(123)
# Make artificial DF
destination <- rep(LETTERS[1:5], each = 2)
airline <- rep(c("Alaska", "AM West"), times = 5)
percent_ontime <- ceiling(runif(10, 70, 99))

df <- data.frame(destination, airline, percent_ontime)
df
#>    destination airline percent_ontime
#> 1            A  Alaska             79
#> 2            A AM West             93
#> 3            B  Alaska             82
#> 4            B AM West             96
#> 5            C  Alaska             98
#> 6            C AM West             72
#> 7            D  Alaska             86
#> 8            D AM West             96
#> 9            E  Alaska             86
#> 10           E AM West             84
# make airline a factor and define order of levels
# df$airline <- factor(df$airline, levels = c("AM West", "Alaska"))
df$airline <- factor(df$airline, levels = c("Alaska", "AM West"))

ggplot(
  data = df,
  aes(
    x = percent_ontime,
    y = fct_rev(destination),
    fill = fct_rev(airline)
  )
) +
  geom_bar(stat = "identity", color = "black", position = position_dodge()) +
  geom_text(aes(label = percent_ontime),
    vjust = -0.3,
    position = position_dodge(0.9), size = 3.5
  ) +
  scale_fill_brewer(palette = "Paired", breaks = rev) +
  theme_minimal()

© www.soinside.com 2019 - 2024. All rights reserved.