I want to plot just values which are less or equal a certain number (let's say 15). I can find these values in one column of my dataframe and if these values aren't less or equal 15, I don't want to plot them.
Can you help me find a solution?
I want to plot just values which are less or equal a certain number (let's say 15). I can find these values in one column of my dataframe and if these values aren't less or equal 15, I don't want to plot them.
Can you help me find a solution?
0. Produce a minimal example
(This step should normally be taken by the one who asks the question; which is one of the reasons your question was downvoted so often)
import numpy as np; np.random.seed(4)
import matplotlib.pyplot as plt
import pandas as pd
plt.rcParams["figure.figsize"] = 5,3
x = np.linspace(2.1,6.3,num=70)
y = np.cumsum(np.random.normal(size=len(x))*10.)
df = pd.DataFrame({"x":x, "y":y})
plt.plot(df.x,df.y)
plt.show()
Now you have several options:
1. Limit the view
You can simply limit the view of the plot such that its y scale only goes up to 15. This is done via
plt.ylim(-30,15)
2. Filter the dataframe
You can filter the dataframe by a condition. This means that in the resulting dataframe only those rows where the condition is meat are present.
df2 = df[df.y <= 15]
plt.plot(df.x,df.y, label="original")
plt.plot(df2.x,df2.y, label="filtered to y <= 15")
As can be seen, the values above 15 are not in the filtered curve. However, it also looks like the new curve beeing continuous, which may be confusing depending on what graph is desired.
3. Setting all values above 15 to nan
Values in a dataset which are nan
(not a number) are not plotted. This can be used, by setting all values above 15 to nan.
df2 = df.copy()
df2[df2.y > 15] = np.nan
plt.plot(df2.x,df2.y, label="y > 15 set to nan")
Appendix: Using two different conditions
You can use several conditions by combining them with logical operators like &
("and") or |
("or").
So setting all values which are either above 15 or below -15 to nan, you'd do
df2[(df2.y > 15) | (df2.y < -15)] = np.nan