7

I am trying to plot a numpy array in such a way that all the points with the same y-axis value should be connected in the a straight line. But some how I am unable to achieve this.

import numpy as np
import matplotlib as mp
import matplotlib.pyplot as plt

# Declare numpy array with nans
x=np.array([np.nan,10005,10005,10006,10006,10006,10007,10007,10007, 10008,10007,10008,10008,10008, np.nan,10010,10010,10010, np.nan, np.nan, np.nan, np.nan])

# Plot the points
plt.plot(x, marker="o", linestyle='-')

# Display the plot in the window
plt.show()

This results in: enter image description here

But I would like the plot to be:

enter image description here

Also, if there is a way to add some margin at the top and bottom of the plot to display the boundary points clearly.

2
  • 2
    The naive solution would be to make a list of lists of all equal y values and plot those as lines separately. Commented Jan 14, 2014 at 22:11
  • 1
    If you want more control over the figure, for example to control the margin, you might as well create Figure and Axes objects, which makes it easier to set all kinds of things for the figure (and its axes). Like fig, axes = plt.subplots() Commented Jan 14, 2014 at 22:21

1 Answer 1

4

Loop over a unique list of your y-values (I've changed the labeling to make things clearer). You'll need a set of x-values too, these are implicitly the same as your plot but we need the locations.

import numpy as np
import matplotlib as mp
import matplotlib.pyplot as plt

# Declare numpy array with nans
y=np.array([np.nan,10005,10005,10006,10006,10006,10007,10007,10007, 10008,10007,10008,10008,10008, np.nan,10010,10010,10010, np.nan, np.nan, np.nan, np.nan])
x=np.arange(y.size)

for yv in np.unique(y):
    if yv != np.nan:
        idx = y == yv
        plt.plot(x[idx],y[idx],marker='o',linestyle='-',color='b')
plt.margins(.1,.1)
plt.show()

Using plt.margins you can give yourself some space from the plot intersecting the border.

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

Nice approach, better than my naive solution
@IvoFlipse It is the naive solution :). The only difference is you use masks to create the lists on the conditional rather than build them explicitly.
Oh wait, I though it was indexing single values, missed the line where you create a mask to see if y == yv. Still neat solution :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.