0

I want to plot only positive values when plotting a graph (like the RELU function in ML)

This may well be a dumb question. I hope not.

In the code below I iterate and change the underlying list data. I really want to only change the values when it's plot time and not change the source list data. Is that possible?

#create two lists in range -10 to 10
x = list(range(-10, 11))
y = list(range(-10, 11))

#this function changes the underlying data to remove negative values
#I really want to do this at plot time
#I don't want to change the source list. Can it be done?
for idx, val in enumerate(y):
    y[idx] = max(0, val)

#a bunch of formatting to make the plot look nice
plt.figure(figsize=(6, 6))
plt.axhline(y=0, color='silver')
plt.axvline(x=0, color='silver')
plt.grid(True)

plt.plot(x, y, 'rx')

plt.show()
0

2 Answers 2

2

I'd suggest using numpy and filter the data when plotting:

import numpy as np
import matplotlib.pyplot as plt

#create two lists in range -10 to 10
x = list(range(-10, 11))
y = list(range(-10, 11))

x = np.array(x)
y = np.array(y)

#a bunch of formatting to make the plot look nice
plt.figure(figsize=(6, 6))
plt.axhline(y=0, color='silver')
plt.axvline(x=0, color='silver')
plt.grid(True)

# plot only those values where y is positive
plt.plot(x[y>0], y[y>0], 'rx')

plt.show()

This will not plot points with y < 0 at all. If instead, you want to replace any negative value by zero, you can do so as follows

plt.plot(x, np.maximum(0,y), 'rx')
Sign up to request clarification or add additional context in comments.

4 Comments

If you are anyway converting to NumPy arrays, I would simply say x = np.arange(-10, 11) and y = np.arange(-10, 11) rather than first creating lists and then converting to arrays.
@Bazingaa Sure, but I suppose the lists are just placeholders for the real data and I cannot know where the real data is coming from. So this answer is strikt in meeting the requirement of "not change the source list data".
This is pretty cool. Thanks for your help. Question: Why use "np.zeros_like(y)" instead of just putting a zero there? A zero works.
Sorry, I typed that from the top of my head. You are right, the documentation says "They must have the same shape, or shapes that can be broadcast to a single shape.". Will update the answer.
0

It may look a bit complicated but filter the data on the fly:

plt.plot(list(zip(*[(x1,y1) for (x1,y1) in zip(x,y) if x1>0])), 'rx')

Explanation: it is safer to handle the data as pairs so that (x,y) stay in sync, and then you have to convert pairs back to separate xlist and ylist.

Comments

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.