Axle Max
Axle Max

Reputation: 825

Matplotlib compute values when plotting - python3

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()

Upvotes: 0

Views: 52

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339660

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')

Upvotes: 2

tif
tif

Reputation: 1484

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.

Upvotes: 0

Related Questions