Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
832 views
in Technique[技术] by (71.8m points)

plot - how add a point to the end of the graph without rebuilding in R

I have vector x, and i build chart

x = rnorm(n = 100, mean = 0.5, sd = 1)
plot(x, type = 'l')

futher, i get new point, for example:

y = 2

how add this point in the end of chart, but without rebuilding?

Wrong way:

x = c(x,y)
plot(x, type = 'l')
question from:https://stackoverflow.com/questions/65886068/how-add-a-point-to-the-end-of-the-graph-without-rebuilding-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To add just that one extra point, you can use:

y = 2
lines(c(100,101), c(x[100], y))

Graph with one additional point

However, if you are going to add more than one point, you will need some extra space on the right side of your graph for the new points, so you might make your initial graph with something like

plot(x, type = 'l', xlim=c(1,110))

This leaves room for 10 extra points.

More detailed explanation
In your original graph, the horizontal axis is the index - in the case of your example, the numbers 1 to 100. The vertical axis is your value, x. To add the extra point y=2 to your graph, you are adding a 101st point, so you need to connect the point (100, x[100]) to (101, y). The function lines adds line segments to existing graphs, so we use

lines(c(100,101), c(x[100], y))

to add the needed segment.

When you made the original plot, R included a little extra space around the graph so there was room for the one extra point. But R only left a little extra. If you try to add very many extra points, you will go outside of the range of the graph and will not be able to see the added points. So if you know that you will be adding extra points, leave extra room in the original graph. For example, if you will be adding ten extra points, say y = seq(2, 2.9, 0.1) the horizontal axis will need to go up to 110, so add xlim=c(1,110) to the original plot.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...