Home > database >  How can i plot two column vectors in 2 different y axis in one plot in ggplot in R?
How can i plot two column vectors in 2 different y axis in one plot in ggplot in R?

Time:10-26

I have a data frame that looks like this:

library(tidyverse)
date = seq(as.Date("2022/1/1"), as.Date("2022/1/12"), by = "day");date
v1 = rnorm(12,0,1);length(date)
v2 = rnorm(12,10,1)
df = data.frame(date,v1,v2);df
         date          v1        v2
1  2022-01-01 -0.27742001 10.649777
2  2022-01-02  0.45117594  9.552337
3  2022-01-03 -0.57960540  8.377525
4  2022-01-04  0.03795781  9.016521
5  2022-01-05 -0.58670684 10.893805
6  2022-01-06 -0.10260160 10.445416
7  2022-01-07 -0.31061137  9.863794
8  2022-01-08 -0.01944977  8.859400
9  2022-01-09 -0.33269714 10.035201
10 2022-01-10  0.38196430  9.953147
11 2022-01-11  0.72070334  8.328117
12 2022-01-12 -0.71014679  8.046312


i want to plot the column v2 in the secondary axis.How can i do this in R?

my effort is the following:

p = ggplot() 
 geom_line(data =df,aes(x=date,y=v1),size=1) 
 scale_x_date(date_labels="%d",date_breaks  ="1 day") 
 scale_y_continuous(sec.axis = sec_axis(v2, name="v2"));p

but reports me an error :

Error in `sec_axis()`:
! Can't convert `trans`, a double vector, to a function.

Any help ?

CodePudding user response:

To plot your second column add a second geom_line. And to fix the error you have to pass a function to the first argument of sec_axis aka the trans argument. This function is used to transform the range of the primary axis. If you don't need any transformation then use the identity function trans = ~ .x:

set.seed(123)

library(ggplot2)

ggplot(data = df)  
  geom_line(aes(x = date, y = v1, color = "v1"), size = 1)  
  geom_line(aes(x = date, y = v2, color = "v2"), size = 1)  
  scale_x_date(date_labels = "%d", date_breaks = "1 day")  
  scale_y_continuous(sec.axis = sec_axis(~ .x, name = "v2"))

  • Related