简体   繁体   中英

why do I get an error when I try to limit my y-axis with ylim function in r

I am failing to edit my y limit values to the desired scale. This is the code:

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

But when i remove the ylim=c(0,25000) it does not bring the error. I want to apply that to another similar data set with non uniform scales.

You need to use the ylim() function from 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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM