firmo23
firmo23

Reputation: 8404

Create a filled area line plot with annotated scatters using plotly

I want to create a filled area plot with line and scatters like in the screenshot attached but I do not know how could add scatters for every year of x-axis and also annotate its value. My code is:

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

enter image description here

Upvotes: 0

Views: 267

Answers (1)

tamtam
tamtam

Reputation: 3671

The mode lines+markers+text allows you to define a line plot with markers and add some text.

I changed the type of year from factor to numeric, because I had to expand the xaxis for readabilty of the annotations.

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

enter image description here

Upvotes: 1

Related Questions