将线添加到R中不同Y轴上的barplot中 [英] Adding lines to barplot in a different Y-axis in R

查看:159
本文介绍了将线添加到R中不同Y轴上的barplot中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单的数据。我希望将V与D1,D2,D3值作为并排条形图以及累积和CS1,CS2,CS3作为直线并以不同的Y值绘制。虽然如 First Figure 中所示绘制并排柱状图比较容易, a>我发现很难为CS1-CS3列添加线图。最终情节看起来像第二张图
感谢您的帮助

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


推荐答案

首先,您需要绘制barplot并将其保存为对象。该对象包含条形的x坐标。由于最大值是39.5,我设置了 xlim = c(0,40)

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

要添加新图,请使用 par(新= TRUE)。然后为第一行添加 plot(),为其他行添加 lines()。由于新图的x值使用第二行 mp 对象(midle bars)。用于设置轴刻度的函数 axis()

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

这篇关于将线添加到R中不同Y轴上的barplot中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆