Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set points outside plot to upper limit

Maybe this question exists already, but I could not find it.

I am making a scatter plot in Python. For illustrative purposes, I don't want to set my axes range such that all points are included - there may be some really high or really low values, and all I care about in those points is that they exist - that is, they need to be in the plot, but not on their actual value - rather, somewhere on the top of the canvas.

I know that in IDL there is a nice short syntax for this: in plot(x,y<value) any value in y greater than value will simply be put at y=value.

I am looking for something similar in Python. Can somebody help me out?

like image 714
user1991 Avatar asked Oct 06 '16 11:10

user1991


2 Answers

you can just use np.minimum on the y data to set anything above your upper limit to that limit. np.minimum calculates the minima element-wise, so only those values greater than ymax will be set to ymax.

For example:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0., np.pi*2, 30)
y = 10. * np.sin(x)

ymax = 5

fig, ax = plt.subplots(1)
ax.scatter(x, np.minimum(y, ymax))

plt.show()

enter image description here

like image 61
tmdavison Avatar answered Sep 21 '22 04:09

tmdavison


There is no equivalent syntactic sugar in matplotlib. You will have to preprocess your data, e.g.:

import numpy as np
import matplotlib.pyplot as plt

ymin, ymax = 0, 0.9
x, y = np.random.rand(2,1000)
y[y>ymax] = ymax
fig, ax = plt.subplots(1,1)
ax.plot(x, y, 'o', ms=10)
ax.set_ylim(ymin, ymax)
plt.show()
like image 29
Paul Brodersen Avatar answered Sep 17 '22 04:09

Paul Brodersen