Removing the line between two specific data points

2020-03-24 06:48发布

I am going to draw a graph in Matlab. The graph is quite simple and I am using the plot function. Suppose the data that I want to plot is (0:1:10). I also put markers on my graph. Then, we have a line that has markers on coordinates (0,0),(1,1),(2,2),... etc.

Now, I want to remove the line between (2,2) and (3,3) without deleting the whole line. That is to say, my purpose is to get rid of a particular segment of the line without loosing the entire line or any marker points.

How can I do that?

2条回答
太酷不给撩
2楼-- · 2020-03-24 07:35

Removing the section of line after you have plotted it is difficult. You can see that the line is made up of one MATLAB object by the following code:

x = 1:10;
y = 1:10;
H = plot(x, y, '-o');
get(H, 'children')

ans =

Empty matrix: 0-by-1

We can see that the line has no children, so there are no 'subparts' that we can remove. However, there are some cheeky tricks we can use to try to achieve the same effect.


Plot two lines separately

...using hold on. See Victor Hugo's answer. This is the proper way of achieving our goal.


Plot two separate lines in one

MATLAB doesn'y plot points with a NaN value. By modifying the input vectors, you can make MATLAB skip a point to give the effect of a broken line:

x = [0 1 2 2 3 4 5 6 7 8 9];
y = [0 1 2 nan 3 4 5 6 7 8 9];
plot(x, y, '-o');

This is equivalent to plotting a line from [0, 0] to [2, 2], skipping the next point, then starting again at [3, 3] and continuing to [9, 9].

enter image description here


'Erase' part of the line

This is the nastiest way of doing it, but is a cheap hack that could work if you can't be bothered with changing your input arrays. First plot the line:

x = 1:10; y = 1:10;
plot(x, y, '-o');

enter image description here

Now plot a white line over the part you wish to erase:

hold on
plot([2 3], [2 3], 'w');

enter image description here

As you can see, the result doesn't quite look right, and will respond badly if you try to do other things to the graph. In short, I wouldn't recommend this method but it might come in useful in desperate times!

查看更多
看我几分像从前
3楼-- · 2020-03-24 07:41

Try the following:

y = [0.2751 0.2494 0.1480 0.2419 0.2385 0.1295 0.2346 0.1661 0.1111];
x = 1:numel(y);

plot(x(1:4), y(1:4), '-x')
hold
plot(x(5:end), y(5:end), '-x')

Graph result

查看更多
登录 后发表回答