无法从ggplot对象转换为plotly

问题描述

我刚刚建立了一个新的玻璃容器,我试图随着时间的推移监视湿度水平,以确保将其设置为最佳的植物生长,我想我应该使用R来做到这一点。我正在使用POSIXct记录日期/时间湿度测量值,然后将其记录到ggplot中,然后尝试将其转换为绘图对象。不幸的是,这最后一步不起作用。我不确定是什么原因造成的,因为我对Plotly的经验很少。这是我的代码;我很抱歉,如果是凌乱的/不至于草率,我是a)累了b)一个学生,所以也欢迎任何提示!@H_502_1@

注释掉绘图线时,我得到了(这就是我想要的):@H_502_1@

Output Plot

@H_502_1@

如果我可以将日期标签从特定时间每6小时“锚定”一次,我也很喜欢-使用scale_x_datetime时限/休息时间取决于多少次测量,我想在00:00、06休息一下每天:00、12:00和18:00。我该怎么办?@H_502_1@

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)

解决方法

下面的代码段适用于plotly,不幸的是标题未带下划线。

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似乎不了解“表达式”语法,因此引起了问题。希望这对您的项目足够好。