简体   繁体   中英

How to draw dual axes in ggplot2?

I am a novice. I am trying to draw a two-coordinate line chart in which the abscissa represents D, the left ordinate represents R, and the right ordinate represents M and A. My data set and code are below, and I want to control the left vertical axis The range of coordinates is (0.9-1.0), and the right is (0.1-0.5), how can I do this?

data<-data.frame(R=c(0.9649789,0.9700804,0.9632690,0.9523244,0.9339738),
             M=c(0.2465927,0.2263204,0.2520991,0.2982259,0.3614747),
             A=c(0.1427684,0.1428706,0.1642165,0.1937662,0.2353444),
             D=c(20,15,10,5,2))

p2<-ggplot(data,
           aes(x = D,y=R))+
     geom_line(color="#6FB585")+
     geom_point(size=3,color="#6FB585")+
     scale_y_continuous(name = 'R',
                 sec.axis = sec_axis(~.*0.25, name = 'M and A'))+
     geom_line(aes(y=M,x=D), color="#E8BF80")+
     geom_point(aes(y=M, x=D),size=3,color="#E8BF80")+
     geom_line(aes(y=A,x=D), color="#A8BF85")+
     geom_point(aes(y=A, x=D),size=3,color="#A8BF85")


  

This might be something to start with:

ggplot(data,
           aes(x = D,y=R))+
    geom_line(color="#6FB585")+
    geom_point(size=3,color="#6FB585")+
    scale_y_continuous(name = 'R',
                       sec.axis = sec_axis(~(.-0.875)/0.25, name = 'M and A'))+
    geom_line(aes(y = M*0.25+0.875, x= D), color="#E8BF80") +
    geom_point(aes(y=M*0.25+0.875, x=D),size=3,color="#E8BF80")+
    geom_line(aes(y=A*0.25+0.875,x=D), color="#A8BF85")+
    geom_point(aes(y=A*0.25+0.875 , x=D),size=3,color="#A8BF85")

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM