【问题标题】:R - ggplot sort x axis by acsending - factorR - ggplot 通过升序对 x 轴进行排序 - 因子
【发布时间】:2018-04-10 19:21:09
【问题描述】:

我正在使用 ggplot 制作条形图。代码如下:

ggplot(foo, aes(thisCol1IsAFactor, Col2, fill = Col3)) + 
  geom_bar(stat="identity", position   = "dodge") + 
  scale_fill_brewer(palette = "Set1")

我想按升序对 thisCol1IsAFactor 进行排序;让它沿 x 轴增加。 thisCol1IsAFactor 列的顺序如下:

7/31/2017
7/31/2017
7/31/2017
7/31/2017
8/7/2017
8/7/2017
8/7/2017
8/7/2017

有重复的日期,因为每个观察都有自己的日期。条形图工作并且看起来很棒,除了排序/排序使它有点难以阅读。日期不会沿 x 轴按时间顺序显示。

【问题讨论】:

  • 可能使用as.Date() 将日期列转换为实际的日期对象(注意格式参数!)。此外,还有geom_col 专门用于避免您在输入stat = "identity" 时使用geom_bar
  • 我会试试的!太棒了!
  • 那不起作用.. 它在条之间放置一个空格并且没有列出日期

标签: r ggplot2


【解决方案1】:

你必须添加这个功能:

scale_x_discrete(thisCol1IsAFactor)

ggplot(foo, aes(thisCol1IsAFactor, Col2, fill = Col3)) + 
  geom_bar(stat="identity", position   = "dodge") + 
scale_x_discrete(thisCol1IsAFactor) +
  scale_fill_brewer(palette = "Set1")

【讨论】:

    【解决方案2】:

    因子自动按字母顺序排序(将数字视为字符串) - 这就是排序不佳的原因。您需要将它们视为日期。试试

    library(tidyverse)
    
    foo %>%
    mutate(
      Col1AsDate = as.Date(thisCol1IsAFactor, "%m/%d/%Y")
    ) %>%
    ggplot(aes(Col1AsDate, Col2, fill = Col3)) + 
      geom_bar(stat="identity", position   = "dodge") + 
      scale_fill_brewer(palette = "Set1")
    

    您也可以手动重新排序所有因素,但这要容易得多。

    【讨论】:

      猜你喜欢
      • 2011-11-17
      • 2019-12-27
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 2013-12-01
      • 2014-09-29
      相关资源
      最近更新 更多