在每个子图上放置几个散点图

问题描述

我有一个数据框,可以使用以下代码创建该数据框:

x = data.frame(metrics=c("type1","type1","orders","mean","mean"),hr=c(6,7,8,6,8),actual=c(14,20,34,22,24,27,56,12,11,15,45,78,89,111,123,156),time=c("today","yesterday","today","yesterday"))

我想使用plot_ly函数可视化此数据。我想为“指标”列中的每种类型的值创建三个子图。另外,在每个子图上,“时间”列(今天,昨天)中每种类型的值都必须有两个散点图。

除了将“时间”列中每种值的两种散点图设置为不同的颜色外,我已经做了所有事情:

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)

我得到这张图:

enter image description here

如何使每个子图中的这两个散点图具有不同的颜色?

解决方法

这就是我想你所追求的:

library(plotly)

x = data.frame(metrics=c("type1","type1","orders","mean","mean"),hr=c(6,7,8,6,8),actual=c(14,20,34,22,24,27,56,12,11,15,45,78,89,111,123,156),time=c("today","yesterday","today","yesterday"))


plot <- function(df) {
  subplotList <- list()
  for(metric in unique(df$metrics)){
    subplotList[[metric]] <- df[df$metrics == metric,] %>%
      plot_ly(
        x = ~ hr,y = ~ actual,name = ~ paste(metrics," - ",time),colors = ~ time,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(width = 1.5)
        ),width = 680,height = 420
      )
  }
  subplot(subplotList,nrows = length(subplotList),margin = 0.1)
}

plot(x)

result

Previous question供将来的读者使用。

相关问答

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