Home > OS >  Can if_else be used in ggplot to change ylim depending on the data?
Can if_else be used in ggplot to change ylim depending on the data?

Time:04-08

I wrote a shinyapp to allow people draw preset graphs from a very specific datafile. They upload the file, select the data to plot and get a nice neat ggplot picture to download. I want to make one of the graphs more dynamic, depending on the data in the table. The variable in the column AirFlow in the example below can come in 3 ranges of interest: equal/under 2.5, equal/under 5 and under 10. I was thinking about using if_else to dictate the parameters for ylim, but I'm not sure if it can be used this way. I'd prefer not to create another variable vector, shinyapps are already complicated to me and I managed to forget the basics since I wrote this one!

The code for the graph in question (in normal ggplot format) and the error below:

> ggplot(df, aes(hrs, AirFlow)) 
 geom_line(size = 1, color = "#00B388") 
 scale_x_continuous(breaks = breaks_extended(n = 10)) 
 if_else(max(df$AirFlow <= 2.5) == 1, ylim(0, 3), if_else(max(df$AirFlow <= 5) == 1, ylim(0, 6),  ylim(0, 10)))

Error in true[rep(NA_integer_, length(condition))] : object of type 'environment' is not subsettable

CodePudding user response:

Perhaps just do this?:

yl = case_when(max(df$AirFlow)<2.5~3,max(df$AirFlow)<=5~6,TRUE~10)

ggplot(df, aes(hrs, AirFlow)) 
  geom_line(size = 1, color = "#00B388") 
  scale_x_continuous(breaks = breaks_extended(n = 10)) 
  ylim(0,yl)

CodePudding user response:

Would something like the following work for you?

ggplot(df, aes(hrs, AirFlow)) 
geom_line(size = 1, color = "#00B388") 
scale_x_continuous(breaks = breaks_extended(n = 10)) 
ylim( 0, ifelse(  max(df$AirFlow  <= 2.5) == 1, 
             3 ,
             ifelse(  max(df$AirFlow  <= 5) == 1,
                      6,
                      10)))
  • Related