问题
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 of car that was sold on each day. So lets say I have the dataframe called ** df1 **
id date Value
Honda 10/30/12 2
Honda 10/31/12 3
Honda 11/1/12 3
Merc 11/2/12 4
Merc 10/30/12 1
Merc 10/31/12 2
Toyota 11/1/12 3
Toyota 11/3/12 2
Now I want three lines(one line for each type of car) on the same x axis.
I tried using the filter()
function inside plotly in the y axis
argument as shown below:
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"))
However I am getting the error
Error: Tibble columns must have consistent lengths, only values of length one are recycled: * Length 3: Column
y
* Length 8: Columnx
Call `rlang::last_erro()
I get that its throwing an error, due to having more x values while being given less y values, how do I cater it?
回答1:
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"))
来源:https://stackoverflow.com/questions/56953875/plotting-graphs-lines-based-on-column-values-from-the-same-datafram-using-plotly