简体   繁体   中英

How to plot week for each year on x axis in plot_ly.(R Language)

I have a data set which is as follows:

在此处输入图片说明

I want to plot the actual and fitted on Y axis for X-axis which will show week and year.

I made a new variable named Year_Week and tried plotting it as it x-axis takes ascending order data. The data is plotting correctly but I am struggling with the naming of X-axis.

在此处输入图片说明

This is the plot_ly code I am using.

output$plot_forecast <- renderPlotly({
data <- forecast_data()
plot <- plot_ly(data, type = "scatter", mode = 'lines') %>% 
  add_lines(x = ~ data$year_week, 
            y = ~ data$actual, 
            name ="Actual",
            line=list(color="Red")) %>%
  add_lines(x = ~ data$year_week, 
            y = ~ data$fitted, 
            name ="Predicted",
            line=list(color="Green")) %>%
  layout(title = "Total Sales (Actual vs Predicted)",
         xaxis = list(title = "Year Week"),
         yaxis = list (title = "Total POS Sales"),
         legend = list(x = 100, y = 0.5))
return(plot) })

The x-axis currently shows 201.49K means 9th Week of 2014, 201.53K means 3rd week of 2015.

I need x-axis to be better than these numbers.

How about you do it in ggplot, with a bit of a workaorund:

    df$YearWeek=paste(df$Year,"Week",df$Week,sep="_")
df0=df%>%select(YearWeek,Actual,Fitted)%>%melt(id.vars="YearWeek")
ggplot(df0,aes(x=YearWeek,y=value,col=variable,group=variable))+geom_line()+
  theme(axis.text.x = element_text(angle = 45))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM