1

I want to create a stacked area plot based on a data frame.

Time <- c("W37/19","W38/19","W39/19","W40/19","W41/19")
Basis <- c(20.07,20.07,20.07,20.07,20.07)
AdStock <- c(5.88,5.60,5.34,5.09,4.86)
TV <- c(0,0,0.54,0.93,1.14)
Display <- c(0.07,0.21,0.33,0.35,0.36)

df_graph <- data.frame(Time, Basis, AdStock, TV, Display)

Data is time series data, "Time" is German calender weeks and should stay in this order.

First thing I do is transforming the data in long format.

library(tidyr)    
df_graph <- pivot_longer(df_graph[,c("Time","Basis","AdStock","TV","Display")],-Time)

Second I convert df_graph$name to a factor and reverse the order, because I want to keep the original order for the stacking.

library(forcats)
df_graph$name <-factor(df_graph$name, levels = c("Basis","AdStock","TV","Display"))
df_graph$name <- fct_rev(df_graph$name)

Then I want to plot my data.

library(ggplot2)
p <- ggplot(df_graph, aes(x=Time, y=value, fill=name))
p <- p + geom_area()
p

The plot shows both axes as well as the legend but no data.

If I replace the calender weeks in "Time" by just an ascending series of numbers

df_graph$Time <- seq(1:5)

it works, but not with my X-Axis values.

Also I don't think, that the conversion of "Name" to factor is a problem, because I still don't get data in my plot even if I remove these two lines.

I tried different methods for the Long-Format (e.g. gather) and also tried using the ascending series of numbers(1:5) as x-values and then replacing it with scale_x_discrete but my areas always disappear.

What am I missing?

Many thanks in advance.

setX
  • 45
  • 3
  • 1
    Try with adding the group aes, i.e. `group = name`. – stefan Sep 16 '20 at 13:22
  • str(df_graph$Time) – Markus Sep 16 '20 at 13:27
  • @stefan: Many thanks, it worked! I spent over an hour figuring out what was wrong but didn't think about trying this.. Thanks – setX Sep 16 '20 at 13:30
  • It originates from your x axis values `$Time` not being defined as continuous. If numeric (your `seq()` example, for instance), `ggplot` will know how to "connect" them across the x axis. As it stands, your value is discrete, so `ggplot` would not know they they are connected. Setting `group` let's `ggplot` know that they are connected and you can get a plot... although the data is still discrete. You may want to check the `lubridate` package for dealing with time. Alternatively, ]stick with week #, and then you can set labels via `scale_x_*` functions. – chemdork123 Sep 16 '20 at 16:01

0 Answers0