如何将连续日期转换为诗歌类别?

问题描述 投票:1回答:2

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

enter image description here

如果尝试使用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"))

如何转换Year列,以便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
2个回答
2
投票

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")

enter image description here


0
投票

我们可以单独使用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')

-输出

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.