【问题标题】:Failed conversion from ggplot object to plotly从 ggplot 对象转换为 plotly 失败
【发布时间】:2020-08-23 21:43:55
【问题描述】:

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

当注释掉情节线时,我得到了这个(这就是我想要的):

如果我可以将日期标签“锚定”到某个时间每 6 小时一次,我也很高兴 - 使用 scale_x_datetime 限制/中断因测量次数而异,我想在 00:00、06 休息每天:00、12:00 和 18:00。我该怎么做?

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 在这行有问题:ggtitle(~""*underline(Vivarium~Humidity~Levels))。你真的需要标题下划线吗?
  • @Dave2e 感谢您的回复!我删除了这条线和 theme() 线但是现在我只得到一个空的绘图框:prnt.sc/u4mkfm 使用 plot_ly 也对我不起作用,它给出了同样的问题(代码与 data.forplot 相同): plotlyplot = plot_ly(data.forplot, type = 'scatter', mode = 'lines', x = ~measurement.time, y = ~humidity, text = ~paste('Time: ', measurement.time, '\n'), hoverinfo = 'text' ) print(plotlyplot)

标签: r ggplot2 plotly ggplotly


【解决方案1】:

下面的代码 sn-p 可以配合 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 似乎不理解“表达式”语法,因此导致了问题。希望这对您的项目来说已经足够好了。

【讨论】:

  • 感谢您回来回答!不幸的是,当我获取代码时,绘图查看器是白色的,没有输出 - 我在这里上传了一个链接:imgur.com/DdsUzrL 我不确定问题出在哪里,我尝试将绘图窗口放大,但没有没用。它对你有用吗?
  • 已经离开并使用新版本的 R、Rstudio 和它现在可以工作的所有软件包进行了全新安装。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-06
  • 2018-09-20
  • 1970-01-01
  • 2015-03-08
  • 2014-03-14
  • 1970-01-01
相关资源
最近更新 更多