Search code examples
rggplot2plotlyggplotly

Failed conversion from ggplot object to plotly


I just built a new terrarium and I'm trying to monitor the humidity levels over time to make sure it's set up for optimal plant-growth, and I thought I'd use R to do it. I'm using POSIXct to record date/time humidity measurements which is then recorded into a ggplot which I then try to turn into a plotly object; unfortunately, this last step doesn't work. I'm not sure what is causing it as I have very little experience with plotly. Here is my code; I apologise if it's messy/not up to scratch, I'm a) tired and b) a student so any tips would also be welcome!

When commenting out the plotly line, I get this (which is what I want):

Output Plot

I'd also like it if I could 'anchor' the date labels to every 6 hours from a certain time - using scale_x_datetime limits/breaks varies upon how many measurements, I'd like a break at 00:00, 06:00, 12:00 and 18:00 every day. How can I do that?

library(ggplot2)
library(lubridate)
library(scales)
library(gridExtra)
library(plotly)
library(hrbrthemes)

measurement.time = as.POSIXct(c("2020-08-23 21:45 GMT", "2020-08-23 22:45 GMT"), tz = 'Europe/London', format = "%Y-%m-%d %H:%M")

humidity = c(99,95)

data.forplot = data.frame(measurement.time, humidity)

Sys.setenv(TZ='Europe/London')

viv.plot = ggplot(data.forplot, aes(x = measurement.time, y = humidity)) +
  geom_point() +
  geom_line(alpha = 0.3) +
  ylab("Humidity (%)") +
  scale_y_continuous(limit=c(0,100),oob=squish) +
  scale_x_datetime(name = "Date", date_labels = "%B %d %H:%M") +
  ggtitle(~""*underline(Vivarium~Humidity~Levels)) +
  theme(plot.title = element_text(hjust=0.5, size =18 )) +
  geom_area(fill="#69b3a2", alpha=0.5)

viv.plot = ggplotly(viv.plot)

print(viv.plot)


Solution

  • The following code snippet works with plotly, unfortunately the title is not underlined.

    measurement.time = as.POSIXct(c("2020-08-23 21:45 GMT", "2020-08-23 22:45 GMT"), tz = 'Europe/London', format = "%Y-%m-%d %H:%M")
    humidity = c(99,95)
    data.forplot = data.frame(measurement.time, humidity)
    
    viv.plot = ggplot(data.forplot, aes(x = measurement.time, y = humidity)) +
       geom_point() +
       geom_line(alpha = 0.3) +
       ylab("Humidity") +
       scale_y_continuous(limit=c(0,100),oob=squish) +
       scale_x_datetime(name = "Date", date_labels = "%B %d %H:%M") +
       ggtitle("Vivarium Humidity Levels") +                            #Works
    #   ggtitle(expression(underline("Vivarium Humidity Levels"))) +    #does not work with plotly, works with ggplot
       theme(plot.title = element_text(hjust=0.5, size =18, face="bold" )) +
       geom_area(fill="#69b3a2", alpha=0.5)
    
    print(ggplotly(viv.plot))
    

    Plotly does not seem to understand the "expression" syntax and thus is causing the problem. Hopefully this is good enough for your project.