Home > Mobile >  coord_cartesian Not Working with Stacked Bar Chart and Date Objects in R in Shiny
coord_cartesian Not Working with Stacked Bar Chart and Date Objects in R in Shiny

Time:02-05

I have a straightforward stacked bar chart generated using ggplot2 in Shiny where I'm using date objects:

Data:

reg_year <- as.Date(c("2021-01-01", "2021-01-01", "2021-01-01", "2020-01-01", "2020-01-01", "2019-01-01", "2019-01-01", "2019-01-01", "2018-01-01", "2018-01-01"))

conv_year <- as.Date(c("2019-01-01", "2019-01-01", "2019-01-01", "2020-01-01", "2021-01-01", "2021-01-01", "2021-01-01", "2021-01-01", "2020-01-01", "2020-01-01"))

df <- data.frame(conv_year, reg_year)

In Shiny I am trying to render a stacked bar chart and use coord_cartesian to 'zoom in'

ui: 

outputPlot("myplot")

server: 

output$myplot <- renderPlot ({

ggplot()  
geom_bar(data=df, aes(x= conv_year, fill = reg_year))  
coord_cartesian(xlim = as.Date(c("2020-01-01", "2021-01-01")))

})

The stacked bar plot renders properly without coord_cartesian. However, when I add the line for coord_cartesian I get an empty figure.

Guidance appreciated.

CodePudding user response:

In output$myplot < renderPlot you're missing the second half of the assignment arrow. Otherwise it works fine for me.

CodePudding user response:

I don't know the exact cause of this but apparently in Shiny there are slightly different syntax requirements. conv_year and reg_year are defined as dates in my dataframe in Shiny (not shown here). Apparently, Shiny somehow 'forgets' they are dates when trying to render in ggplot in Shiny. The following renders properly:

server: 

output$myplot <- renderPlot ({

ggplot()  
geom_bar(data=df, aes(x= as.Date(conv_year), fill = reg_year))  
coord_cartesian(xlim = as.Date(c("2020-01-01", "2021-01-01")))

})

conv_year needs to be explicitly stated as a date for x in aes but fill must not be a date.

I don't know why these differences occur but they do.

  •  Tags:  
  • Related