ggplotly and geom_bar when using dates - latest ve

2020-06-06 07:19发布

问题:

Say you have the following df:

x <- as.Date(c("1963-06-01", "1964-06-01", "1965-06-01","1966-06-01"))
y <- c(1162.7, 975.4, 1280.3, 1380.0)
data<- data.frame(x, y)

when you plot it using ggplot, everything seems to work:

ggplot(data = data, aes(x = x, y = y)) +
      geom_bar(stat = "identity")

ggplot works

However, if we add a ggplotly wrap around it, the graph disappears.

ggplotly(ggplot(data = data, aes(x = x, y = y)) +
      geom_bar(stat = "identity"))

ggplotly doesn't work

I get a warning message that says:

We recommend that you use the dev version of ggplot2 with ggplotly().

Now, if I remove the date format, the gglotly does work.

x <- c("1963-06-01", "1964-06-01", "1965-06-01","1966-06-01")
y <- c(1162.7, 975.4, 1280.3, 1380.0)
data<- data.frame(x, y)

ggplotly(ggplot(data=data) + 
  geom_bar(aes(x = x, y = y), stat = "identity"))

So, there seems to be an issue with ggplotly handling geom_bar with dates. Is there a way to solve this?

回答1:

This appears to be a problem in Mac and seems to be related with the way geom_bar handles dates.

I found that adding as.POSIXct() fixes the issue.

x <- c("1963-06-01", "1964-06-01", "1965-06-01","1966-06-01")
y <- c(1162.7, 975.4, 1280.3, 1380.0)
data<- data.frame(x, y)

ggplotly(ggplot(data=data) + 
  geom_bar(aes(x = as.POSIXct(x), y = y), stat = "identity"))


标签: r ggplot2 plotly