Hallie Sheikh
Hallie Sheikh

Reputation: 431

How to include a second axis in ggplot with another dataframe?

I have 2 dataframe. The first dataframe is

df1
Year        BP
1 1550 -0.004343344
2 1551  0.033794533
3 1552  -0.0034535036
4 1553  0.054935152
5 1554  0.029320574
6 1555  -0.001854373

I plot the ggplot for above dataframe1 by :

ggplot(df1,aes(Year,BP))+geom_line(aes(color="IP"),lwd=1)

Now I would like to add a second y axis on the right hand side corner of that very same ggplot for the below data frame df2 and also labelled as “second axis”. I want to include variables of CL, PR and NR on that same plot. How can this be achieved in R? Note to serve as an example I only provided 5 years,but in reality I have 100+ years.

df2
Year      V1         U   CL         PR          FO   NR
1   1550 7377211     0 0.03615170 0.1405466      0 0.8232772
2   1551 7377212     0 0.03622309 0.1397468      0 0.8240073
3   1552 7377213     0 0.03631065 0.1389448      0 0.8247278
4   1553 7377214     0 0.03639766 0.1381439      0 0.8254495
5   1554 7377215     0 0.03647239 0.1373441      0 0.8261718
6   1555 7377216     0 0.03655438 0.1365248      0 0.8269085

EDIT: This is what I tried so far:

f<-ggplot()+ 
geom_line(data=df1, aes(x=Year, y=NBP), color="red")

f+geom_line(data=df2, aes(x=Year, y=CL ), color="blue")+
  scale_y_continuous(limits=c(-0.1, 0.2),
                     sec.axis = sec_axis(~ . +1, name = "Land Fraction")
  )

Is there any to add the PR and NR to this plot?

Upvotes: 0

Views: 965

Answers (1)

r2evans
r2evans

Reputation: 160942

Lacking more context, one of the reasons it took so long for ggplot2 to support multiple axes is that they often occlude or confuse the reader. If not done carefully and clearly, they can suggest things about the data that are not true. I suggest that perhaps a better way to model this data graphically would be using facets

Might I suggest faceting instead?

library(dplyr)   # bind_rows, %>%
library(tidyr)   # pivot_longer
library(ggplot2)
bind_rows(
  pivot_longer(df1, -Year),
  pivot_longer(df2, -Year)
) %>%
  ggplot(aes(Year, value)) +
  geom_line() +
  facet_wrap(~ name, ncol = 3, scales = "free_y")

ggplot2, faceted

(I demoed this using dplyr and tidyr, though this can be done in other dialects of R include base R and data.table.)

Upvotes: 1

Related Questions