2

I have the following data set (class: dataframe)

data2 <- read.table(text =
"Date         S        D
199011  1.023247 1.009845
199012  1.050828 1.015818
199101  1.066754 1.023077
199102  1.147112 1.033462
199103  1.160859 1.042610
199104  1.164412 1.049691
199105  1.204586 1.058778
199106  1.173015 1.063795
199107  1.220449 1.074115
199108  1.210946 1.075537
199109  1.219717 1.076117
199110  1.256516 1.080941
199111  1.220505 1.087333
199112  1.288720 1.100406
199201  1.306862 1.106454
199202  1.304459 1.108409
199203  1.255841 1.111392
199204  1.243667 1.113684
199205  1.286353 1.126754
199206  1.262842 1.131144
199207  1.283566 1.138307", header = TRUE)

I wish to produce a plot, which contains two functions. An example with multiple functions is shown in the image below:

Multiple functions in one plot

I have written the following (abridged) code:

library(ggplot2)
ggplot(data2, aes(Date)) +              
geom_line(aes(y= D), colour="red") +  
geom_line(aes(y=S), colour="green") + 
ylab(label="Return") + 
scale_x_continuous(name="Date", limits = c(1990, 2017))

I am able to produce a plot with the desired axis, but no functions are shown. I have tried multiple solutions, but with no luck.

Does anyone have an idea of how I can proceed?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Mads
  • 123
  • 2
  • 7

1 Answers1

6

How about the following?

library(tidyverse);
df %>%
    gather(what, value, S:D) %>%
    ggplot(aes(Date, value, colour = what)) +
    geom_line()

It's often preferable to reshape the data from wide to long, and then add a different aesthetic (here colour) to map the different curves. dplyr::gather converts your data from wide to long, where what encodes the column.

enter image description here


Sample data

df <- read.table(text =
    "Date         S        D
199011  1.023247 1.009845
199012  1.050828 1.015818
199101  1.066754 1.023077
199102  1.147112 1.033462
199103  1.160859 1.042610
199104  1.164412 1.049691
199105  1.204586 1.058778
199106  1.173015 1.063795
199107  1.220449 1.074115
199108  1.210946 1.075537
199109  1.219717 1.076117
199110  1.256516 1.080941
199111  1.220505 1.087333
199112  1.288720 1.100406
199201  1.306862 1.106454
199202  1.304459 1.108409
199203  1.255841 1.111392
199204  1.243667 1.113684
199205  1.286353 1.126754
199206  1.262842 1.131144
199207  1.283566 1.138307", header = T)
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68