Matplotlib is connecting the last to the first point when plotting

Issue

I am drawing a figure using the script below. When I plot the figure, the last point is connected to the first point. How can I remove this last line drawing ? Note that everything else seems ok.

I have attempted to do a for loop over the first to last point and the result is shown in the below image.

enter image description here

fig = pl.figure()
ax = fig.add_subplot(111)
xValues = []
yValues =[]
for tr in range(105,300,5):
 tr = tr/100.
 for pr in range(0,1500,1):
   pr = pr / 100. 
   result = compressiblityFactor(pr,tr,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11)
   ##result = compressiblityFactor(p,t,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,specificGravity)

   xValues.append((pr))
   yValues.append(result)

pl.plot(xValues,yValues)

pl.show()

Solution

How the plot in matplotlib is drawn:

You send to plot a couple of points and it draws it from one to another. In your code you construct several curves but you doesn’t draw each of it separately, you send all of them to plot. So it draws the first curve, reaches its end and starts to draw the next. But! It doesn’t know that there is another curve, it thinks that it is the part of the one very-big-complicated-curve, so the plot draws that annoying line. If you want to draw them separately, you should move pl.plot(xValues,yValues) into the first for and empty xValues, yValues after it. Here is the example of my code (compressiblityFactor is replaced by a random func):

import matplotlib.pyplot as pl
import math

fig = pl.figure()
ax = fig.add_subplot(111)

for tr in range(105,300,5):
    xValues = []
    yValues = []
    tr = tr/100.
    for pr in range(0,1500,100):
        pr = pr / 100. 
        result = pr*pr*math.sin(tr*40)
        xValues.append(pr)
        yValues.append(result)
    pl.plot(xValues,yValues)

pl.show()

Answered By – vurmux

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published