【问题标题】:My ggplot bar chart reorder() function isn't working我的 ggplot 条形图 reorder() 函数不起作用
【发布时间】:2019-12-02 21:16:39
【问题描述】:

我正在尝试将条形图重新排序为降序(联系率最高的道路组位于顶部)。但是 reorder() 函数似乎不起作用。

    for (i in uniq_wards) 
  { print(ggplot(data = subset(roads, Ward == i),
               aes(x = reorder(Roadgroup, Contact.rate),
                   y = Contact.rate,
                   fill = undecided_rate)) +
          geom_col() +
          coord_flip() +
          labs(fill = "Undecided rate", y = "Contact Rate", x = "Road Group") +
          theme(axis.text.x = element_text(angle = 90),
                text = element_text(size = 8)) +
          scale_fill_gradient(low = "gray", high = "blue", limits=c(0.0, 0.35)) +
          ggtitle(i, subtitle = "Contact Rate and Undecided Density")) 
  }

Example ggplot

第二个图像是我希望第一个图看起来像的降序示例,它使用相同的变量轴 reorder() 代码:

x = reorder(Roadgroup, Contact.rate),
                   y = Contact.rate,

Working example

【问题讨论】:

标签: r ggplot2


【解决方案1】:

没有数据很难提供帮助。您可以尝试以下方法。我只在您的原始代码中添加了FUN = sum。如果它不起作用,请提供一些示例数据。

library(tidyverse) 
    for (i in uniq_wards) 
  { print(ggplot(data = subset(roads, Ward == i),
               aes(x = reorder(Roadgroup, Contact.rate, FUN = sum),
                   y = Contact.rate,
                   fill = undecided_rate)) +
          geom_col() +
          coord_flip() +
          labs(fill = "Undecided rate", y = "Contact Rate", x = "Road Group") +
          theme(axis.text.x = element_text(angle = 90),
                text = element_text(size = 8)) +
          scale_fill_gradient(low = "gray", high = "blue", limits=c(0.0, 0.35)) +
          ggtitle(i, subtitle = "Contact Rate and Undecided Density")) 
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2017-06-20
    • 2013-06-02
    相关资源
    最近更新 更多