使用ggplot更改构面图中的x标签顺序

时间:2018-08-27 14:13:53

标签: r ggplot2

我正在尝试按字母顺序绘制下面的构面图,我尝试了多种方法,甚至尝试去除构面并仅绘制了Overpaid vs比例图,但是该图仍然具有字母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), ]

Dataframe with frequency added

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

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

Plot with x axis in alphabetical order

2 个答案:

答案 0 :(得分:0)

在您的第六行

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

更改为多付2

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

答案 1 :(得分:0)

您可以使用forcats::fct_reorder()重新排列因子水平,或者将水平从"a"更改为"e",然后传递一个命名向量(名称匹配因子级别)作为标签参数的scale_x_discrete()

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

enter image description here

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)

enter image description here