3

How can I plot a two point line segment plot as shown in the following figure enter image description here

The data is like below

x = [1,2,3,4,5,6]

y = [1.2,1.2,-2.1, -2.1, 4.1, -4.1] #these y values are always in pair such that I need a solid line to connect these equivalent values and then a dotted line between this pair and the next pair.

gogo
  • 219
  • 4
  • 13
  • possible duplicate of http://stackoverflow.com/questions/21352580/matplotlib-plotting-numerous-disconnected-line-segments-with-different-colors – derricw Oct 02 '15 at 23:00

2 Answers2

4

Does this achieve what you were hoping?

import numpy as np
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5, 6]
y = [1.2, 1.2, 2.1, 2.1, -4.1, -4.1]

plt.plot(x, y, 'm--')

pair_x_array = np.reshape(x, (-1, 2))
pair_y_array = np.reshape(y, (-1, 2))
for i, pair_x in enumerate(pair_x_array):
    pair_y = pair_y_array[i]
    plt.plot(pair_x, pair_y, 'm', linewidth=3)

plt.show()
SimonBiggs
  • 816
  • 1
  • 8
  • 18
3

Do you mean something like this?

import pylab
xdata = [0, 1, 2, 3, 4, 5]
ydata = [0, 1, 2, 2, 1, 0]
# Assuming xdata, ydata are of suitable length and type
plots = [pylab.plot(xdata[i:i + 2], ydata[i:i + 2], **whatever_keyword_arguments) for i in xrange(0, len(xdata), 2)]
pylab.show()

Edit after OP edit:

I see what you mean, and it's trivial to add the lines in dashes.

def plot_broken(xseq, yseq, even=True, **plot_kwargs):
    size = len(xseq)
    assert size == len(yseq)
    assert size % 2 == 0
    start = 0 if even else 1
    return [pylab.plot(xseq[i:i + 2], yseq[i:i + 2], **plot_kwargs)
            for i in xrange(start, size, 2)]
plots = plot_broken(xdata, ydata, even=True, color="m",
                    linestyle="solid")
plots += plot_broken(xdata, ydata, even=False, color="m",
                     linestyle="dashed")
Cong Ma
  • 10,692
  • 3
  • 31
  • 47