I am trying to make a stacked area chart in R exactly like this ggplot2 one (below) only using plotly.
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, var set = _.curry( _.rearg(_.set, [2, 0, 1]), 3 );
, 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
, I use the following code to make my plotly chart:
elw_stack
That code generates this chart:
The issue is that the plotly labels refer to the cumulative 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)
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?
答案 0 :(得分:3)
我遇到了类似的问题并最终决定不使用ggplotly,而是使用了plot_ly函数。以下是我与您的数据一起使用的代码:
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"))
这就是最终情节的样子:
我能够工作的是使用for循环添加不同的跟踪。我想编写一个函数,它将一个具有任意列数的数据框作为输入并返回堆积区域图,但由于某种原因,该图不会显示所有迹线(仅限第一个和最后一个)
希望它有所帮助...