在 R 中使用 Plotly 时,月份未显示在 x 轴上

问题描述 投票:0回答:1

如标题所述。这是当前代码:

    start_date <- as.Date(input$dateRange[1])
    end_date <- as.Date(input$dateRange[2])
    month_seq <- seq(from = start_date, to = end_date, by = "month")
    
    data$Month <- as.Date(data$Month)
    
    p <- ggplot(data, aes(x = Month, y = AvgRating)) +
      geom_line() + 
      geom_point(aes(text = paste("Avg: ", round(AvgRating, 2), "<br>Count: ", Count))) +
      scale_x_date(date_breaks = "1 month", date_labels = "%b %Y") +
      theme_minimal() +
      labs(title = "Average Rating by Month", x = "", y = "Average Rating")
    
    plotly_graph <- ggplotly(p, tooltip = "text") %>%
      layout(xaxis = list(
        type = 'date',
        tickmode = "array",
        tickvals = month_seq,
        tickformat = "%b %Y",
        dtick = "M1")
      )
    
    plotly_graph

不确定这是否重要,但它正在 r Shiny 应用程序的服务器部分中运行。 Ch*tgpt 一直让我绕圈子。

r shiny plotly
1个回答
0
投票

我在没有plotly::layout规范的情况下复制了你的代码,它似乎可以工作。我在 x 轴上有几个月...... 如果默认布局已达到预期结果,为什么还要添加布局? 这里

df <- 
  tibble(
   Month = seq(as.Date("2019-01-01"),
               as.Date("2019-12-01"),
               by = "month") 
  ) |> 
  mutate(AvgRating = sample(100,nrow(df)),
         Count = sample(20,nrow(df)))

p <- ggplot(df, aes(x = Month, y = AvgRating,
                    group = 1,
                    text = 
                      paste("Avg: ", round(AvgRating, 2),
                            "\nCount: ", Count))) +
  geom_line() + 
  geom_point() +
  scale_x_date(date_breaks = "1 month", date_labels = "%b %Y") +
  theme_minimal() +
  labs(title = "Average Rating by Month", x = "", y = "Average Rating")

library(plotly)
plotly_graph <- ggplotly(p, tooltip = "text")

plotly_graph
© www.soinside.com 2019 - 2024. All rights reserved.