Search code examples
rdataframeggplot2scale

How to plot data with negative value in a clear way using ggplot?


For example, I have a dataframe like this:

df=data.frame(
 year=2001:2020,
 pre=c(8.5018000 , -7.7160000 ,  7.0916000 , -5.0360000 , -7.7912000
 , -11.8490000 , 26.1540000,  -9.2820000 , -8.5530000 ,  0.5976900
,   6.6069000,  -6.2534000, -11.4280000 , -0.0079124  , 6.0739000
,  14.7270000 , 29.4790000, -15.8340000 ,  4.1739000, -19.6560000),
 tmp=c(0.702760, -1.077300, -1.058300 ,-0.882200 ,-0.491940,  2.048100,
 -0.999390,  0.308870,  1.107600, -0.042847,  0.452430 ,-0.329630,
0.636950,  1.484700,  0.434400,  0.079248, -0.503850, -0.710800,
0.025189, -1.183900)
)

If I just plot tmp,its variation can be observed clearly.Howexver,if I add the pre to ggplot,the tmp can not be observed clearly.

ggplot(df)+
  geom_line(aes(x=year,y=tmp),col='red')

enter image description here

ggplot(df)+
  geom_line(aes(x=year,y=tmp),col='red')+
  geom_line(aes(x=year,y=pre))

enter image description here

How to plot it clearly?

-------------------------------------------------------------------------------------------------------------

Thanks for all reply and comments.I try to rescale them because of some reasons.The following problem is that it not give legend automatically.

ggplot(df)+
  geom_line(aes(x=year,y=scale(tmp)),col='red')+
  geom_line(aes(x=year,y=scale(pre)),col='blue')+
  geom_text(aes(x=year,y=scale(tmp)),label=2001:2020)+
  geom_text(aes(x=year,y=scale(pre)),label=2001:2020)+
  scale_x_continuous(breaks = 2001:2020,name=NULL)+
  scale_y_continuous(name=NULL)

enter image description here


Solution

  • You could add a secondary axis:

    ggplot(df, aes(year, pre/10)) +
      geom_line(col = "red") +
      geom_line(aes(y = tmp)) +
      scale_y_continuous(name = "tmp",
                         sec.axis = sec_axis(~.x * 10, name = "pre")) +
      theme_minimal(base_size = 16) +
      theme(axis.text.y.right = element_text(color = "red"),
            axis.title.y.right = element_text(color = "red"))
    

    enter image description here

    Or use facets:

    ggplot(tidyr::pivot_longer(df, -year), aes(year, value, color = name)) +
      geom_line() +
      facet_grid(name~., scales = "free") +
      scale_color_manual(name = NULL, values = c("black", "red")) +
      theme_bw(base_size = 16) +
      theme(axis.text.y.right = element_text(color = "red"),
            axis.title.y.right = element_text(color = "red"))
    

    enter image description here