首页 文章

通过x轴上的数字数据排序ggplot条形图,而不是y轴上的字母顺序

提问于
浏览
0

我正在尝试按x轴排序我的ggplot geom_bar图表中的数据,这是整数值(Crude.Rate =每种疾病的死亡人数),但y轴,美国各州,按字母顺序保存数据 . 我试图创建x轴数值数据的因子,但图表按字母顺序排列,x轴标签只是移动以匹配y轴 .

码:

stDis10 <- cdcData %>%
  filter(Year == "2010", ICD.Chapter == "Heart Attack") %>%
  arrange(desc(Crude.Rate)) %>%
  select(State, ICD.Chapter, Crude.Rate)

stDis10$Crude.Rate <- factor(stDis10$Crude.Rate, levels = stDis10$Crude.Rate)

ggplot(stDis10, aes(y = Crude.Rate, x = State)) + geom_bar( stat='identity') + coord_flip()

1 回答

  • 0

    您无需将Crude.Rate更改为一个因子 . 你可以按Crude.Rate重新排序State:

    ggplot(stDis10, aes(y = Crude.Rate, x = reorder(State, Crude.Rate))) + geom_col() + coord_flip()
    

    (在最新版本的ggplot2中,可以使用 geom_col() 代替 geom_bar(stat = "identity") . )

相关问题