Homer Jay Simpson
Homer Jay Simpson

Reputation: 1280

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

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 ?

Upvotes: 2

Views: 85

Answers (2)

TarJae
TarJae

Reputation: 78927

Here is an alternative:

library(tidyverse)

coeff <- 10
ggplot(df, aes(x = date)) +
  geom_line(aes(y=v1, color="v1", linetype="v1"), size = 1)+
  geom_line(aes(y=v2/coeff, color="v2", linetype="v2"), size = 1)+
  scale_y_continuous(
    name = "your label",
    sec.axis = sec_axis(~.*coeff, name = "your text")
  )+
  scale_x_date(date_labels = "%d", date_breaks = "1 day") +
  scale_color_manual(values = c("red", "dodgerblue3"))  +
  scale_linetype_manual(values = c(3, 1)) +
  theme_bw(14)+
  theme(
    axis.title.y = element_text(color = "red", size=13, face="bold"),
    axis.title.y.right = element_text(color = "blue", size=13, face="bold"),
    axis.text.x = element_text(angle = 45, vjust = 0.5, hjust=1)
  ) 

enter image description here

Upvotes: 1

stefan
stefan

Reputation: 124183

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"))

Upvotes: 3

Related Questions