【问题标题】:Weekly Line Chart in R Plotly with End of Line LabelR Plotly中的每周折线图,带有行尾标签
【发布时间】:2020-05-15 13:52:34
【问题描述】:

我的数据,称为“x”,类似于以下结构:

   type        eow       url seq  metric
1     a 2019-07-06 / page1 /   7 0.07075
2     a 2019-07-13 / page1 /   7 0.07543
3     a 2019-07-20 / page1 /   7 0.07704
4     a 2019-07-27 / page1 /   7 0.07873
5     a 2019-08-03 / page1 /   7 0.07551
6     a 2019-08-10 / page1 /   7 0.08027
7     a 2019-08-17 / page1 /   7 0.07957
8     a 2019-08-24 / page1 /   7 0.07885
9     a 2019-08-31 / page1 /   7 0.07753
10    a 2019-09-07 / page1 /   7 0.07034

基于该数据,我创建了一个 ggplot 输出,使用以下代码将其包装在 Shiny 应用程序中的 renderPlotly 语句中:

ggplot() + 
  geom_line(data = x, aes(x=eow, y=metric, color=url), size = 1, show.legend = TRUE) +
  geom_text(data = subset(x, eow == max(eow)), aes(label = seq, colour = url, x = eow, y = metric), hjust = -.9) +
  theme_minimal() +
  scale_size_area() +
  xlab("Week Ending") +
  theme(legend.position = "right", axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_x_date(date_breaks = "2 weeks", labels = date_format("%m/%d/%Y")) +
  scale_y_continuous(labels = scales::percent_format(accuracy = 1)) 

但是,当我在图表中添加额外的线条时,数据标签重叠并且 plotly 目前不支持 ggrepel。我转换为 plotly,但我似乎无法强制 x 轴标签按周和两周间隔显示,也无法让数据标签显示在每行的末尾:

plot_ly(data = x, 
        x = ~eow, 
        y = ~metric,
        color = ~url,
        type = 'scatter',
        mode = "lines",
        textposition = 'top center') %>%
  layout(
    xaxis = list(
      autotick = FALSE,
      dtick = "W2",
      type = 'week',
      tickformat = "%m/%d/%Y"
    ))

非常感谢任何帮助。

【问题讨论】:

    标签: r ggplot2 r-plotly


    【解决方案1】:

    添加tickmode = 'array' 会起作用吗?

    library(plotly)
    
    x <-"   type        eow       url seq  metric
         a 2019-07-06   page1     7 0.07075
         a 2019-07-13   page1     7 0.07543
         a 2019-07-20   page1     7 0.07704
         a 2019-07-27   page1     7 0.07873
         a 2019-08-03   page1     7 0.07551
         a 2019-08-10   page1     7 0.08027
         a 2019-08-17   page1     7 0.07957
         a 2019-08-24   page1     7 0.07885
         a 2019-08-31   page1     7 0.07753
         a 2019-09-07   page1     7 0.07034"
    
    x <- read.table(text = x, header = TRUE)
    
    plot_ly(data = x, 
            x = ~eow, 
            y = ~metric,
            color = ~url,
            type = 'scatter',
            mode = "lines",
            textposition = 'top center') %>%
      layout(
        xaxis = list(
          autotick = FALSE,
          dtick = "W2",
          type = 'week',
          tickmode = 'array',
          tickformat = "%m/%d/%Y"
        )) 
    

    【讨论】: