Adding lines to barplot in a different Y-axis in R

2019-03-31 07:59发布

问题:

I've the following simple data. I wish to plot the "V" vs. D1,D2,D3 values as side-by-side bar plots and the cumulative sums,CS1,CS2,CS3 as lines, and at a different Y-scale . While it is relatively easy to plot the side-by-side bar plots as shown in the First Figure I'm finding it difficult to add the line plots for the CS1-CS3 columns. The final plot would look something like the Second Figure Thanks for your help

V   D1  D2  D3  CS1 CS2 CS3
10  2038    1806    1643    72.81171847 64.52304394 58.69953555
20  550 709 757 92.46159343 89.85351911 85.7449089
30  142 192 271 97.53483387 96.71311183 95.42693819
40  45  61  80  99.14255091 98.89246159 98.28510182
50  12  20  30  99.57127546 99.6070025  99.35691318
60  5   6   10  99.74991068 99.82136477 99.71418364
70  2   2   3   99.82136477 99.89281886 99.82136477
80  4   1   2   99.96427295 99.92854591 99.89281886
90  1   0   1   100.0000000 99.92854591 99.92854591
100 0   1   0   100.0000000 99.96427295 99.92854591

回答1:

First, you need to plot barplot and save it as object. This object contains x coordinates for bars. As maximal value is 39.5, I set xlim=c(0,40).

mp<-barplot(as.matrix(t(df[,2:4])),beside=TRUE,xlim=c(0,40),ann=FALSE)
mp
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]  1.5  5.5  9.5 13.5 17.5 21.5 25.5 29.5 33.5  37.5
[2,]  2.5  6.5 10.5 14.5 18.5 22.5 26.5 30.5 34.5  38.5
[3,]  3.5  7.5 11.5 15.5 19.5 23.5 27.5 31.5 35.5  39.5

To add new plot use par(new=TRUE). Then add plot() for first line and lines() for other lines. As x values for new plots used second line of mp object (midle bars). Functions axis() used to set axis ticks.

par(new=TRUE)
plot(mp[2,],df$CS1,xlim=c(0,40),type="l",col="red",axes=FALSE,ylim=c(0,100),ann=FALSE)
lines(mp[2,],df$CS2,col="blue")
lines(mp[2,],df$CS3,col="green")
axis(1,at=mp[2,],labels=df$V)
axis(4,at=seq(0,100,10))
box()



回答2:

The updateusr function in the TeachingDemos package allows you to change the coordinate system of an existing plot without needing to resort to par(new=TRUE) and the potential problems that come with it.

You could also look at the twoord.plot function in the plotrix package as another option.

Having 2 coordinate systems on the same plot can sometimes lead to confusion, it may be better to create 2 aligned plots stacked vertically so that there is no overlap and the scales are completely independent, possibly making the top plot shorter. The layout function can help with this arrangement.



标签: r graphics plot