【问题标题】:How to plot week for each year on x axis in plot_ly.(R Language)如何在 plot_ly 的 x 轴上绘制每年的周数。(R 语言)
【发布时间】:2018-07-31 16:08:26
【问题描述】:

我有一个数据集如下:

我想为 X 轴绘制实际和拟合的 Y 轴,它将显示周和年。

我创建了一个名为 Year_Week 的新变量并尝试绘制它,因为它的 x 轴采用升序数据。数据绘制正确,但我正在努力命名 X 轴。

这是我正在使用的 plot_ly 代码。

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) })

x 轴当前显示 201.49K 表示 2014 年第 9 周,201.53K 表示 2015 年第 3 周。

我需要 x 轴比这些数字更好。

【问题讨论】:

  • 您是否尝试过使用日期创建as.POSIXct() 列并将该列用作x 轴。之后,您可以调整标签以仅列出年份和星期。提供dput(head(data, 12))的输出,你会更快得到答案...
  • @drmariod 你能解释一下如何将x轴标签调整为仅在月份和年份上固定吗?谢谢。

标签: r plot shiny plotly


【解决方案1】:

你在 ggplot 中做这件事怎么样,有点麻烦:

    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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-07
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 2021-08-12
    相关资源
    最近更新 更多