当我尝试用ylim函数限制y轴时为什么会出现错误

时间:2020-09-03 14:54:27

标签: r axis

我无法将y极限值编辑为所需的比例尺。这是代码:

    df <- read.table(text = "Site   Type   Day1   Day2   Day3
          A SD 780 431 295 
                 B SD 350 377 255 
                 B M 480 179 560  
                 A M 240 876 789 
                 C FO 840 179 NA  
                 C FI 350 NA 255 
                 A NF 508 NA 565 
                 B NF 405 876 NA  ", header = TRUE)

library(dplyr)
library(tidyr)
library(ggplot2)

df %>% 
  pivot_longer(cols = -c(Site,Type)) %>%
  mutate(Type = factor(Type,
                       levels = c('SD', 'M', 'NF', 'FO', 'FI'),
                       ordered = T)) %>%
  ggplot(aes(x=Site,y=value,fill=name, ylim=c(0,25000)))+
  geom_bar(stat='identity')+
  facet_wrap(.~Type, scales = 'free_x', ncol = 5, strip.position = "bottom")+
  theme_minimal()+
  theme(strip.placement  = "outside",
        panel.spacing    = unit(0, "points"),
        strip.background = element_blank(),
        strip.background.y = element_blank(),
        panel.background = element_rect(fill = "yellow"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(), 
        strip.text       = element_text(face = "bold", size = 9))+
    scale_color_discrete(name="Legend",label=c("Day 1","Day 2", "Day 3"))

但是,当我删除ylim=c(0,25000)时,不会出现此错误。我想将其应用到另一个具有不同尺度的相似数据集。

1 个答案:

答案 0 :(得分:1)

您需要使用ylim()中的ggplot2函数:

df %>% 
  pivot_longer(cols = -c(Site,Type)) %>%
  mutate(Type = factor(Type,
                       levels = c('SD', 'M', 'NF', 'FO', 'FI'),
                       ordered = T)) %>%
  ggplot(aes(x=Site,y=value,fill=name))+
  ylim(0,25000) + 
  geom_bar(stat='identity')+
  facet_wrap(.~Type, scales = 'free_x', ncol = 5, strip.position = "bottom")+
  theme_minimal()+
  theme(strip.placement  = "outside",
        panel.spacing    = unit(0, "points"),
        strip.background = element_blank(),
        strip.background.y = element_blank(),
        panel.background = element_rect(fill = "yellow"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(), 
        strip.text       = element_text(face = "bold", size = 9))+
  scale_color_discrete(name="Legend",label=c("Day 1","Day 2", "Day 3"))