使geom_bar以升序显示值

时间:2018-09-07 21:38:48

标签: r ggplot2 geom-bar

尽管我的查询以降序显示值,但ggplot然后按字母顺序显示它们,而不是以升序显示。

enter image description here

该问题的已知解决方案似乎无效。他们建议对值使用Reorder或factor,在这种情况下不起作用

这是我的代码:

boxoffice %>%
  group_by(studio) %>%
  summarise(movies_made = n()) %>%
  arrange(desc(movies_made)) %>%
  top_n(10) %>%
  arrange(desc(movies_made)) %>%
  ggplot(aes(x = studio, y = movies_made, fill = studio, label = as.character(movies_made))) +
  geom_bar(stat = 'identity') +
  geom_label(label.size = 1, size = 5, color = "white") +
  theme(legend.position = "none") +
  ylab("Movies Made") +
  xlab("Studio")

2 个答案:

答案 0 :(得分:1)

对于那些想要更完整示例的人,这是我得到的地方:

library(dplyr)
library(ggplot2)

# get some dummy data
boxoffice = boxoffice::boxoffice(dates=as.Date("2017-1-1"))

df <- (
  boxoffice %>%
  group_by(distributor) %>%
  summarise(movies_made = n()) %>%
  mutate(studio=reorder(distributor, -movies_made)) %>%
  top_n(10))

ggplot(df, aes(x=distributor, y=movies_made)) + geom_col()

答案 1 :(得分:0)

您需要将boxoffice$studio转换为有序因子。然后 ggplot 将遵守数据集中的行顺序,而不是按字母顺序排列。您的dplyr链将如下所示:

boxoffice %>%
  group_by(studio) %>%
  summarise(movies_made = n()) %>%
  arrange(desc(movies_made)) %>%
  ungroup() %>% # ungroup
  mutate(studio = factor(studio, studio, ordered = T)) %>% # convert variable
  top_n(10) %>%
  arrange(desc(movies_made)) %>%
  ggplot(aes(x = studio, y... (rest of plotting code)