R 使用plotly创建带注释散点的填充区域线打印

R 使用plotly创建带注释散点的填充区域线打印,r,plotly,R,Plotly,我想创建一个填充区域图,其中包含线和散点,如所附的屏幕截图中所示,但我不知道如何为x轴的每一年添加散点,并对其值进行注释。我的代码是: library(plotly) data <- t(USPersonalExpenditure) data <- data.frame("year"=rownames(data), data) fig <- plot_ly(data, x = ~year, y = ~Food.and.Tobacco, name = 'F

我想创建一个填充区域图,其中包含线和散点,如所附的屏幕截图中所示,但我不知道如何为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
library(plotly)

数据模式
行+标记+文本
允许您使用标记定义线图并添加一些文本

我将
year
的类型从factor改为numeric,因为为了注释的可读性,我必须扩展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)))
library(plotly)
数据%
布局(xaxis=列表(
范围=列表(最小值(数据$year)-1,最大值(数据$year)+1)

谢谢这是基于你的回答