dbraeuni
dbraeuni

Reputation: 11

several return plotting in R

Try to plot very basic data in R.

Year    X1     X2     X3     X4     X5     X6     X7
2004   0.91   0.23   0.28   1.02   0.90   0.95   0.94  
2005   0.57   -0.03  0.88   0.52   0.47   0.55   0.56  
2006   1.30   -0.43  1.95   1.27   1.00   1.19   1.26  
2007   0.44   0.63   0.60   0.34   0.60   0.50   0.46  
2008   1.69   0.34  -2.81  -2.41  -1.80  -1.87  -1.83 

What I am looking for is a basic line chart over time with x = year and y = value and the chart itself should include all X1-X7.

I was looking at the ggplot2 functionality, but I don't know where to start.

# Libraries
library(tidyverse)
library(streamgraph)
library(viridis)
library(plotly)

# Plot
p <- data %>% 
  ggplot(aes(x = year, y = n) +
    geom_area() +
    scale_fill_viridis(discrete = TRUE) +
    theme(legend.position = "none") +
    ggtitle("multiple X over time") +
    theme_ipsum() +
    theme(legend.position = "none")
ggplotly(p, tooltip = "text")

Would anyone give me a hand on it, please? Is there an easy way to do it in basic R?

Thanks.

Upvotes: 0

Views: 37

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545963

It’s unclear what you intend to do with geom_area but in the following you’ll see a basic line chart of the data you’ve shown.

The key point is that ‘ggplot2’ works on tidy data, so you need to first transform your data into long form:

data %>%
    pivot_longer(-Year, names_to = 'Vars', values_to = 'Values') %>%
    ggplot() +
    aes(x = Year, y = Values, color = Vars) +
    geom_line()

enter image description here

Upvotes: 1

Related Questions