You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:使用Matplotlib绘制NumPy的np.where结果时出现空白图

Fixing the Blank Plot for Your 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 x that 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 10:27:41