【问题标题】:Create a filled area line plot with annotated scatters using plotly使用 plotly 创建带有注释散点的填充区域线图
【发布时间】:2023-03-04 20:28:01
【问题描述】:

我想创建一个带有线和散点的填充区域图,如附加的屏幕截图中所示,但我不知道如何为 x 轴的每一年添加散点并注释其值。我的代码是:

library(plotly)

data <- t(USPersonalExpenditure)
data <- data.frame("year"=rownames(data), data)

fig <- plot_ly(data, x = ~year, y = ~Food.and.Tobacco, name = 'Food and Tobacco', type = 'scatter', mode = 'line', stackgroup = 'one', fillcolor = '#F5FF8D')
fig

【问题讨论】:

    标签: r plotly


    【解决方案1】:

    lines+markers+text 模式允许您使用标记定义线图并添加一些文本。

    我将 year 的类型从因子更改为数字,因为我必须扩展 xaxis 以提高注释的可读性。

    library(plotly)
    
    data <- t(USPersonalExpenditure)
    data <- data.frame("year" = as.numeric(rownames(data)), data)
    
    plot_ly(data,
            x = ~year, 
            y = ~Food.and.Tobacco,
            text = ~Food.and.Tobacco) %>%
      add_trace(
        type = 'scatter',
        mode = 'lines+markers+text',
        fill = 'tozeroy',
        fillcolor = '#F5FF8D',
        marker = list(color = 'black'),
        line = list(color = 'black'),
        textposition = "top center",
        hovertemplate = paste0("<b>%{x}</b>
                               Cummulative Food and Tobacco: %{y} 
                              <extra></extra>"),
        hoveron = 'points') %>%
      layout(xaxis = list(
        range= list(min(data$year) - 1, max(data$year) + 1)))
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多