Plotting graphs lines based on column values from the same datafram using Plotly

后端 未结 1 1838
梦如初夏
梦如初夏 2021-01-27 13:32

I am trying to plot a line graph of different types of cars sold per day in ** plotly ** on ** R **. The way the graph would look is that, it would have line graphs of each type

相关标签:
1条回答
  • 2021-01-27 13:41

    I didn't see the same error (without trace type specified, it drew a histogram).

    library(plotly)
    
    df1 <- data.frame(
      id = c("Honda", "Honda", "Honda", "Merc", "Merc", "Merc", "Toyota", "Toyota"),
      date = c('10/30/12', '10/31/12', '11/1/12', '11/2/12', '10/30/12', '10/31/12', '11/1/12', '11/3/12'),
      Value = c(2, 3, 3, 4, 1, 2, 3, 2)
    )
    
    df1$date <- as.Date(df1$date, "%m/%d/%y")
    
    plot_ly(df1,x=~date)%>% 
      add_trace(y=filter(df1,id=="Honda")$value,name="Honda",mode="lines+markers")%>%
      add_trace(y=filter(df1,id=="Merc")$value,name="Honda",mode="lines+markers")%>%
      add_trace(y=filter(df1,id=="Toyota")$value,name="Honda",mode="lines+markers")%>%
      layout(xaxis=list(title="Date"),yaxis=list(title="Cars Sold"))
    
    > plot_ly(df1,x=~date)%>% 
    +   add_trace(y=filter(df1,id=="Honda")$value,name="Honda",mode="lines+markers")%>%
    +   add_trace(y=filter(df1,id=="Merc")$value,name="Honda",mode="lines+markers")%>%
    +   add_trace(y=filter(df1,id=="Toyota")$value,name="Honda",mode="lines+markers")%>%
    +   layout(xaxis=list(title="Date"),yaxis=list(title="Cars Sold"))
    No trace type specified:
      Based on info supplied, a 'histogram' trace seems appropriate.
      Read more about this trace type -> https://plot.ly/r/reference/#histogram
    

    You don't need to filter by each car type. Instead use group_by before calling plot_ly --- perhaps this is what you had in mind:

    df1 %>%
      group_by(id) %>%
      plot_ly(x=~date, y=~Value, type='scatter', color=~id, mode="lines+markers") %>%
      layout(xaxis=list(title="Date"),yaxis=list(title="Cars Sold"))
    

    0 讨论(0)
提交回复
热议问题