如何在闪亮的ggplot2中和绘图地组合来自不同数据的条形图和折线图?

时间:2019-07-02 15:31:26

标签: r ggplot2 shiny plotly

我的代码无效。我不知道为什么。

此折线图是表格数据df,此条形图来自熔化后的数据df。条形图y为“ SavedDemandCharge”和“ NewDemandCharge”,线形图y为“ Demand_KW”。他们的x都是两个月。

我多次更改了代码,但仍然无法正常工作。

  output$plot1 <- renderPlotly({
    df <- df_form()
    df$DemandCharge <- as.numeric(gsub('[$,]','', df$DemandCharge))
    df$NewDemandCharge <- as.numeric(gsub('[$,]','', df$NewDemandCharge))
    df$SavedDemandCharge<- df$DemandCharge-df$NewDemandCharge
    df$month <- format(as.Date(df$Startdate), "%Y-%m")
    mydata<-melt(df,id= c("month","Startdate","Enddate","DemandCharge", "Season",
                          "EnergyUsage_KWh","OnpeakUsage_KWh","NewOnpeakUsage_KWh","Demand_KW",
                          "NewDemand_KW","TotalCharge","NewTotalCharge"))
    mydata$variable <- fct_relevel(mydata$variable, "SavedDemandCharge")
    #plot 1#
    plotly1<-ggplot(data = mydata, aes(x = month, y = value, fill = variable)) + 
      geom_bar(stat = "identity",width = 0.6)+
      scale_fill_manual(values=cbPalette1)+ scale_y_continuous("Cost",labels = dollar)
  
    #plot 2#  
    plotly<- plotly1 + geom_line(data=df, aes(x=month, y=Demand_KW, group=1))+geom_point()
    ggplotly(plotly)
    
  })

0 个答案:

没有答案