Search code examples
rplotlystacked-area-chart

plotly labels in R stacked area chart


I am trying to make a stacked area chart in R exactly like this ggplot2 one (below) only using plotly. enter image description here

Here is a link to my data.

To generate a plotly version of the above ggplot2 chart, I first have to add the values of each column in my dataframe, elw, on top of the values in the previous column like so. This is because plotly (as far as I'm aware) does not have the ability to automatically stack values in area charts.

With this new stacked data set, elw_stack, I use the following code to make my plotly chart:

el_plot2 = ggplot() +
  geom_area(aes(elw_stack$year, elw_stack$x99999, fill = 'green')) +
  geom_area(aes(elw_stack$year, elw_stack$x20000, fill = 'red')) +
  geom_area(aes(elw_stack$year, elw_stack$x19000, fill = 'blue')) +
  geom_area(aes(elw_stack$year, elw_stack$x12018, fill = 'purple')) +
  geom_area(aes(elw_stack$year, elw_stack$x10006, fill = 'yellow'))

ggplotly(el_plot2)

That code generates this chart: enter image description here

The issue is that the plotly labels refer to the cumulative elw_stack values. The green value pictured at year 1999 is actually ~3700 (i.e. 11,365 - 7957). But the description bar says the cumulative value of 11,365. Is there a way to fix this so that the labels aren't cumulative values?


Solution

  • I was having a similar problem and eventually decided not to use ggplotly, but instead i used the plot_ly function. Here is the code I used with your data:

    elw <- read.csv("elw.csv")
    elw_stack <- read.csv("elw_stack.csv")
    
    plot <- plot_ly(data=elw_stack, x=year, y=x10006, fill="tonexty", mode="lines",
                    text=round(elw$x10006, 0), hoverinfo='x+text+name', name="x10006")
    
    plot <- add_trace(plot, data=elw_stack, x=year, y=x12018, fill="tonexty", mode="lines",
                      text=round(elw$x12018,0), hoverinfo='x+text+name', name="x12018")
    
    plot <- add_trace(plot, data=elw_stack, x=year, y=x19000, fill="tonexty", mode="lines",
                      text=round(elw$x19000,0), hoverinfo='x+text+name', name="x19000")
    
    plot <- add_trace(plot, data=elw_stack, x=year, y=x20000, fill="tonexty", mode="lines",
                      text=round(elw$x20000,0), hoverinfo='x+text+name', name="x20000")
    
    plot <- add_trace(plot, data=elw_stack, x=year, y=x99999, fill="tonexty", mode="lines",
                      text=round(elw$x99999,0), hoverinfo='x+text+name', name="x99999")
    
    plot <- layout(plot, yaxis=list(title="Whatever title you wanna use"))
    

    And this is how the final plot looks:

    plotly image

    What I can't get to work is to add the different traces using a for loop. I wanted to write a function that takes a data frame with an arbitrary number of columns as input and returns the stacked area plot, but for some reason the plot won't show all the traces (only first and last)

    Hope it helps...