Search code examples
rplotlysubplot

How to get subplot to show two ploty plots?


I am trying to generate two simple plots of the same block side by side using subplot but only one of the plots is shown.

size = 50000
width = 4
x1 = 0
x2 = width
y1 = 0
y2 = size

p1 <- plot_ly(type='area',mode='none',x = c(x1,x2,x2,x1,x1),width = 500, height = 725,
          y = c(y1,y1,y2,y2,y1),
          fill = 'toself',
          fillcolor = 'rgb(233,87,62)')

x1 = 0
x2 = width
y1 = 0
y2 = size

p2 <- plot_ly(type='area',mode='none',x = c(x1,x2,x2,x1,x1),width = 500, height = 725,
         y = c(y1,y1,y2,y2,y1),
         fill = 'toself',
         fillcolor = 'rgb(233,87,62)')

subplot(p1,p2,nrows=1)

Solution

  • To properly create a area chart with plotly, start with a scatter chart and then set mode to "lines".

    Here is example with a better sample dataset:

    library(plotly) 
    p1 <- plot_ly(economics, type='scatter', x = ~date, y = ~uempmed, 
              name = 'Left chart',
              fill = 'tozeroy', 
              mode = 'lines', 
              fillcolor = 'rgb(233,87,62)', 
              line = list(color = 'rgb(233,87,62)'))
    
    p2 <- plot_ly(economics, type='scatter', x = ~date, y = ~unemploy, 
                  name = 'Right chart',
                  fill = 'tozeroy', mode = 'lines', fillcolor = 'rgb(87,87,62)', 
                  line = list(color = 'rgb(87,87,62)'))
    
    subplot(p1, p2,  nrows = 1, margin = 0.05, widths =  c(0.6, 0.4))
    

    enter image description here