求助:使用Matplotlib绘制NumPy的np.where结果时出现空白图
y Data in Matplotlib Hey there! Let's break down why your plot for y is showing up blank and get it displaying properly.
The Root of the Problem
When you run y = np.where(x > 0.75), you're not getting the actual values of x that are greater than 0.75—you're getting a tuple containing the indices of those values in the original x array. Matplotlib can't plot this tuple directly, which is why you end up with a blank plot.
How to Fix It
You have a couple of straightforward options to visualize the data you care about:
Option 1: Plot the Values > 0.75 with Scatter Points
This method lets you clearly see where the values above 0.75 sit in your sequence, along with their actual values:
import numpy as np from matplotlib import pyplot as plt # Generate your data np.random.seed(1000) x = np.random.uniform(size=1000) # Plot the original uniform data plt.plot(x, label='Original uniform sequence') plt.title("Uniform distribution of the sequence", fontsize=18) # Extract indices and corresponding values where x > 0.75 indices = np.where(x > 0.75)[0] # Grab the first element of the tuple (the index array) y_values = x[indices] # Plot these points as red scatter markers plt.scatter(indices, y_values, color='crimson', s=12, label='Values > 0.75') # Add a legend for clarity plt.legend() plt.show()
Option 2: Highlight the Points Directly on the Original Curve
If you prefer to keep the original line plot and just highlight the relevant points, you can use a masked array to only show values above 0.75:
import numpy as np from matplotlib import pyplot as plt np.random.seed(1000) x = np.random.uniform(size=1000) plt.plot(x) plt.title("Uniform distribution of the sequence", fontsize=18) # Create an array where values > 0.75 stay, others are set to NaN (Matplotlib ignores NaNs) y_masked = np.where(x > 0.75, x, np.nan) # Plot the masked values as red circles plt.plot(y_masked, 'ro', markersize=6) plt.show()
What These Changes Do
- Both approaches target the actual values in
xthat meet your condition, not just their indices. - The scatter plot makes it easy to correlate the position (index) of each high value with its magnitude.
- The masked array method keeps your original line intact while drawing attention to the points you care about.
内容的提问来源于stack exchange,提问作者nikhil nik

