在R中绘制plot_ly图的子图

问题描述

我有一个数据框,可以通过以下方式创建:

x = data.frame(metrics=c("type1","type1","orders","mean","mean"),hr=c(6,7,8,6,8),actual=c(14,20,34,56,12,78,89))

我试图使用plot_ly函数绘制散点图。我为此编写了一个函数(我需要将其作为一个函数):

plot <- function(df){
  

  gp <- df %>%



    plot_ly(
      x = ~ hr,y = ~ actual,group = ~ metrics,hoverinfo = "text",hovertemplate = paste(
        "<b>%{text}</b><br>","%{xaxis.title.text}: %{x:+.1f}<br>","%{yaxis.title.text}: %{y:+.1f}<br>","<extra></extra>"
      ),type = "scatter",mode = "markers",marker = list(
        size = 18,color = "white",line = list(color = "black",width = 1.5)
    ),width = 680,height = 420
  
)

  gp
}

我得到这个情节:

enter image description here

如您所见,所有三个指标都是一对一的图。我如何使用子图将它们分别放在单独的图上?

解决方法

您必须使用subplot为每个图形创建一个单独的绘图对象。我们可以使用循环来做到这一点:

library(plotly)

x = data.frame(
  metrics = rep(c("type1","orders","mean"),each = 3),hr = c(6,7,8,6,8),actual = c(14,20,34,56,12,78,89)
)


plot <- function(df) {
  subplotList <- list()
  for(metric in unique(df$metrics)){
    subplotList[[metric]] <- df[df$metrics == metric,] %>%
      plot_ly(
        x = ~ hr,y = ~ actual,name = metric,hoverinfo = "text",hovertemplate = paste(
          "<b>%{text}</b><br>","%{xaxis.title.text}: %{x:+.1f}<br>","%{yaxis.title.text}: %{y:+.1f}<br>","<extra></extra>"
        ),type = "scatter",mode = "markers",marker = list(
          size = 18,color = "white",line = list(color = "black",width = 1.5)
        ),width = 680,height = 420
      )
  }
  subplot(subplotList,nrows = length(subplotList),margin = 0.1)
}

plot(x)

result

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...