自动绘制多个散点图

时间:2018-12-04 05:59:27

标签: r shiny plotly

首先,我们在R中创建一个数据集

 n=10

 SlNO<-c(1:n)

 df<-data.frame("SlNo"=SlNO, "Val1"=c(1:10), "Val2"=c(1:10), "Val3"=c(1:10), 
 "Val4"=c(1:10), "Val5"=c(1:10))
  df

接下来,我们使用此数据框创建一个绘图图

   library(plotly)
   plot_ly(data=df, x = ~df[,"SlNo"])%>%
   add_bars( x = ~SlNo, y =~Val2, data = df, inherit = T, marker = 
    list(color 
   = "#82e600"), yaxis = 'y2', name="Val2")%>%
   add_trace(y = ~df[,'Val3'], name = 'Va3',mode = 'line')%>%
   add_trace(y = ~df[,'Val4'], name = 'Val4',mode = 'line')%>%
   add_trace(y = ~df[,'Val5'], name = 'Val5',mode = 'line')%>%
   add_trace(y = ~df[,'Val1'], name = 'Val1',mode = 'line')%>%

     layout(title = 'Chart',
     xaxis = list(title ="SlNo" ),
     yaxis = list(rangemode='tozero',side = 'left', title = 'Count', 
     showgrid = FALSE, zeroline = TRUE),
     yaxis2 = list(side = 'right', overlaying = "y", title = "Val3", 
     showgrid = FALSE, zeroline = TRUE))

图表已生成

下一步,我试图使它自动化,以便如果我改变N,则不需要重写整个公式

我们列出数据框df的名称,并使用

创建一个名为df2的新数据框。
  names1<-names(df)
  df2<-data.frame("SLno"=1:length(names1),'names1'=names1)
  df2<-df2[2:nrow(df2),]

接下来,我们创建公式的第二部分,其中定义了轨迹

 df2$formula<-paste0("add_trace(y=~df[,",df2$names1, "], name =", 
 df2$names1,", mode= 'line')%>%" )

  midpart= df2$formula

我们现在创建公式的第一部分和第三部分

   firstpart=paste0("plot_ly(data=df, x = ~df[,'SlNo'])%>%
   add_bars( x = ~SlNo, y =~Val2, data = df, inherit = T, marker = 
   list(color = '#82e600'), yaxis = 'y2', name='Val2')%>%")




     # create thirdpart
    thirdpart="layout(title = 'Chart',
      xaxis = list(title ='SlNo' ),
      yaxis = list(rangemode='tozero',side = 'left', title = 'Count', 
      showgrid = FALSE, zeroline = TRUE),
      yaxis2 = list(side = 'right', overlaying = 'y', title = 'Val3', 
      showgrid = FALSE, zeroline = TRUE))"




  Now we create the script for the chart


  form1<-(c(firstpart, midpart, thirdpart))

对象form1已创建,但无法呈现图表。我在这里寻求帮助。

0 个答案:

没有答案