【问题标题】:How to convert continuous date into discete category?如何将连续日期转换为离散类别?
【发布时间】:2020-04-23 07:29:43
【问题描述】:

我有一组数据,其中包含来自两个不同年份的值,但在绘制时我无法将其设置为两个离散的类别,而不是连续的日期范围。

如果我尝试使用scale_x_discrete,年份标签将完全消失。

library(ggplot2)
ggplot(df2018, aes(x = Year, y= Weight, fill = Year)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  facet_wrap(~ Species, scale = "free_x") +
  scale_x_discrete("Year", labels = c("2018", "2019"))

如何转换年份列,以便 ggplot 将其读取为两个不同的类别(即 2018 年和 2019 年)?

数据:

structure(list(Species = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 
2L, 3L, 1L, 4L, 5L, 6L), .Label = c("Coralline", "Pocockiella", 
"Gigartina", "Ulva", "Colpomenia", "Sargassum"), class = "factor"), 
    Year = c(2018, 2018, 2018, 2018, 2018, 2018, 2019, 2019, 
    2019, 2019, 2019, 2019), Weight = c(0.83879, 1.61504, 2.32838, 
    6.25983, 8.77286, 115.48649, 0.046695, 0.1373982, 0.392931, 
    0.508436, 0.521956, 90.098115), Percent = c(0.614156130776106, 
    1.18252091399354, 1.70482343825805, 4.58340344080901, 6.42342630865946, 
    84.5583946581545, 0.0508869004261174, 0.149732702047923, 
    0.428205175529173, 0.554079282686656, 0.568812999225068, 
    98.186396971536)), row.names = c(NA, -12L), class = c("tbl_df", 
"tbl", "data.frame"))

【问题讨论】:

    标签: r ggplot2 bar-chart data-visualization geom-bar


    【解决方案1】:

    year 更改为factor 类:

    library(dplyr)
    library(ggplot2)
    
    df %>%
      mutate(Year = factor(Year)) %>%
      ggplot() + aes(x = Year, y= Weight, fill = Year) +
      geom_bar(stat = "identity") +
      coord_flip() +
      facet_wrap(~ Species, scale = "free_x")
    

    【讨论】:

    • 谢谢!无法相信解决方案如此简单。我之前用过as.date,但是没用。
    【解决方案2】:

    我们可以单独使用ggplot 来做到这一点

    library(ggplot2)
    ggplot(df2018, aes(x = Year, y= Weight, fill = as.factor(Year))) +
        geom_bar(stat = "identity") +
       coord_flip() +
       facet_wrap(~ Species, scale = "free_x") +
       scale_x_discrete("Year", labels = c("2018", "2019")) + 
       scale_fill_discrete(name = 'Year')
    

    -输出

    【讨论】:

      猜你喜欢
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      • 2020-11-05
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 2013-04-15
      相关资源
      最近更新 更多