简体   繁体   中英

Connecting grouped dots/points on a scatter plot based on distance

I have 2 sets of depth point measurements, for example:

> a
  depth value
1     2     2
2     4     3
3     6     4
4     8     5
5    16    40
6    18    45
7    20    58

> b
  depth value
1    10    10
2    12    20
3    14    35

I want to show both groups in one figure plotted with depth and with different symbols as you can see here

plot(a$value, a$depth, type='b', col='green', pch=15)
points(b$value, b$depth, type='b', col='red', pch=14)

The plot seems okay, but the annoying part is that the green symbols are all connected (though I want connected lines also). I want connection only when one group has a continued data points at 2 m interval ie the symbols should be connected with a line from 2 to 8 m (green) and then group B symbols should be connected from 10-14 m (red) and again group A symbols should be connected (green), which means I do NOT want to see the connection between 8 m sample with the 16 m for group A.

An easy solution may be dividing the group A into two parts (say, A-shallow and A-deep) and then plotting A-shallow, B, and A-deep separately. But this is completely impractical because I have thousands of data points with hundreds of groups ie I have to produce many depth profiles. Therefore, there has to be a way to program so that dots are NOT connected beyond a prescribed frequency/depth interval (eg 2 m in this case) for a particular group of samples. Any idea?

If plot or lines encounters and NA value, it will automatically break the line. Using that, we can insert NA values for missing measurements in your data and that would fix the problem. One way is this

rng<-range(range(a$depth), range(b$depth))
rng<-seq(rng[1], rng[2], by=2)

aa<-rep(NA, length(rng))
aa[match(a$depth, rng)]<-a$value

bb<-rep(NA, length(rng))
bb[match(b$depth, rng)]<-b$value

plot(aa, rng, type='b', col='green', pch=15)
points(bb, rng, type='b', col='red', pch=14)

Which produces

情节

Note that this code assumes that all depth measurements are evenly divisible by 2.

I'm not sure if you really have separate data.frames for all of your groups, but there may be better ways to fill in missing values depending on your real data structure.

We can use the fact that lines will but breaks in when there is a NA , like MrFlick suggests. There might be a simpler way, though:

#Merge the two sets together
all = merge(a,b,by='depth', all=T)
#Plot the lines
plot(all$value.x, all$depth, type='b', col='green', pch=15)
points(all$value.y, all$depth, type='b', col='red', pch=14)

在此处输入图片说明

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