【问题标题】:Change order of x label in facet plot using ggplot使用ggplot更改构面图中x标签的顺序
【发布时间】:2018-08-27 14:13:53
【问题描述】:

我正在尝试按字母顺序绘制下面的分面图,我尝试了多种方法,甚至尝试摆脱分面并仅绘制 Overpaid 与比例,但该图仍然有一个按字母顺序排列的 x 轴.

最初我尝试为每个元素分配一个频率值,然后按该值对列表进行排序,但这并没有改变情节。

overpaid_each_country <- survey_df %>%
 filter(!is.na(Overpaid)) %>%
  filter(Country %in% Country_Sum$Var1) 

overpaid_each_country <- overpaid_each_country[ , which(names(overpaid_each_country) %in% c("Overpaid","Country"))]

overpaid_each_country <- transform(overpaid_each_country, freq = ave(seq(nrow(overpaid_each_country)), Overpaid, FUN=length))

overpaid_each_country <- overpaid_each_country[order(overpaid_each_country$freq), ]

然后我尝试设置因子水平,但尽管因子水平发生了变化,但情节没有。

overpaid_each_country %>% 
mutate(Overpaid2 = factor(Overpaid, levels = c("Greatly overpaid", "Somewhat overpaid", "Greatly underpaid", "Neither underpaid nor overpaid", "Somewhat underpaid"))) %>%
  ggplot(aes(x = Overpaid2, y = ..prop.., group = 1)) +
 geom_bar( color = "white", fill = "#42dff4") +
  facet_wrap(~ Country, nrow = 4)  +
  aes(stringr::str_wrap(Overpaid, 10)) +
  xlab("OverPaid orUnderpaid") +
  ylab("Proportion of Respondents")+
  labs(title = "Are you Overpaid or Underpaid?") +
  theme(axis.title.x=element_blank(), axis.text.y=element_text(size=12), axis.text.x = element_text(size=12), plot.title = element_text(size = 17))

【问题讨论】:

标签: r ggplot2


【解决方案1】:

您可以使用forcats::fct_reorder() 重新排序因子级别,或者将级别从"a" 更改为"e",然后将命名向量(其中名称与因子级别匹配)传递给@987654328 @ 作为标签参数。

library(ggplot2)
d <- data.frame(
  x = factor(sample(1:5, size = 100, replace = TRUE), labels = c("a", "b", "c", "d", "e"))
)

ggplot(d, aes(x = x, y = ..prop..)) + geom_bar()

labels <- c(a = "Greatly underpaid", b = "Somewhat underpaid", c = "Neither/nor", d = "somewhat overpaid", e = "greatly overpaid")

ggplot(d, aes(x = x, y = ..prop..)) + 
  geom_bar() +
  scale_x_discrete(labels = labels)

【讨论】:

    【解决方案2】:

    在你的第 6 行

     aes(stringr::str_wrap(Overpaid, 10)) +
    

    改为多付2

    aes(stringr::str_wrap(Overpaid2, 10)) +
    

    【讨论】:

      猜你喜欢
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 1970-01-01
      • 2021-09-29
      • 2022-08-15
      • 1970-01-01
      相关资源
      最近更新 更多