matplotlib画散点图大于零红色小于零蓝色
时间: 2023-04-10 16:04:55 浏览: 349
可以使用以下代码来实现:
```python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [3, -2, 4, -1, 5, -3, 6, -4, 7]
colors = ['red' if i > 0 else 'blue' for i in y]
plt.scatter(x, y, c=colors)
plt.show()
```
这段代码会根据 y 值的正负来选择红色或蓝色作为散点的颜色。
相关问题
scatter控制大于某个曲面的点为红色
要在 `scatter` 中将大于某个曲面的点设置为红色,可以通过 `c` 和 `cmap` 参数实现。`c` 参数用于指定每个点的颜色,可以是一个数组,数组中的每个元素表示对应点的颜色。`cmap` 参数用于指定颜色映射,可以是一个字符串或颜色映射对象。可以通过判断每个点的值是否大于某个值,然后为其设置不同的颜色。下面是一个简单的例子,展示如何在 `scatter` 中将大于某个曲面的点设置为红色:
```python
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.random.normal(0, 1, 100)
y = np.random.normal(0, 1, 100)
z = x**2 + y**2
# 设置曲面的阈值
threshold = 1
# 根据阈值生成颜色数组
colors = np.empty(z.shape, dtype=str)
colors[z > threshold] = 'r'
colors[z <= threshold] = 'b'
# 绘制 3D 散点图
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, c=colors, cmap='coolwarm')
plt.show()
```
在这个例子中,我们首先生成了一个 3D 散点图的数据,然后设置了一个阈值 `threshold`,对于大于这个阈值的点,将其颜色设置为红色,小于等于阈值的点,将其颜色设置为蓝色。然后使用 `ax.scatter` 函数绘制 3D 散点图,并将颜色数组 `colors` 作为 `c` 参数传递给函数,将颜色映射 `'coolwarm'` 作为 `cmap` 参数传递给函数。最后使用 `plt.show` 函数显示图形。
Python散点图怎么根据条件更改点的颜色
可以使用 matplotlib 库中的 scatter 函数绘制散点图,并通过条件语句改变点的颜色。具体实现方法如下:
```python
import matplotlib.pyplot as plt
# 生成数据
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [3, 5, 4, 6, 7, 2, 8, 9, 1, 5]
colors = ['b' if i > 5 else 'r' for i in y] # 根据 y 值定义颜色,y > 5 为蓝色,y <= 5 为红色
# 绘制散点图
plt.scatter(x, y, c=colors)
# 设置图像标题和坐标轴标签
plt.title('Scatter Plot with Color Change')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
# 显示图像
plt.show()
```
代码中通过列表解析式根据 y 值的大小定义颜色,将 y 值大于 5 的点设为蓝色,小于等于 5 的点设为红色,并在绘制散点图时传入颜色参数 `c=colors`。如果需要根据其他条件改变颜色,只需要修改颜色列表的生成方式即可。
阅读全文
相关推荐










