firmo23
firmo23

Reputation: 8404

Create a filled area line plot with plotly

I want to create a basic filled area plot with plotly using this dataset:

week<-c(2,1,3)
pts<-c(10,20,30)
wex<-data.frame(week,pts)

The x-axis should contain the week which as you can see may not be in order in the dataset but MUST be in order in the x-axis of the plot. The y axis should contain the pts.

For some reason I take nothing as a result but no error seems to exist.

library(plotly)
week<-c(2,1,3)
pts<-c(10,20,30)
wex<-data.frame(week,pts)

wex$week <- factor(wex$week, levels = wex[["week"]])
p <- plot_ly(x = ~wex$week, y = ~wex$pts,
             type = 'scatter', mode = 'lines',fill = 'tozeroy')


p

Upvotes: 0

Views: 229

Answers (2)

David Klotz
David Klotz

Reputation: 2431

This will work if you want to keep the x-axis, but it's not a pure plot_ly answer:

p <- ggplot(wex, aes(x = week, y = pts)) + 
  geom_point() + 
  geom_line() + 
  geom_ribbon(aes(ymin = 0, ymax = pts), fill = "blue", alpha = .6, group = 1) 
g <-  ggplotly(p)
g

enter image description here

Upvotes: 1

Roman Luštrik
Roman Luštrik

Reputation: 70643

Values on x axis need to be numeric (see example) and ordered.

wex <- wex[order(wex$week), ]

# wex$week <- factor(wex$week, levels = wex[["week"]])
plot_ly(x = ~wex$week, y = ~wex$pts, type = 'scatter', mode = 'lines', 
        fill = 'tozeroy')

enter image description here

Upvotes: 1

Related Questions