欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

在Python中绘制子图的四象限并添加散点图

最编程 2024-02-13 15:30:21
...

python 在子图上绘制四象限,并叠加散点

解决思路:

可以使用 Matplotlibaxvline()axhline() 函数在一个子图上绘制一条十字线,
再使用 Matplotlibfill_between() 函数将子图分成四个象限。

结果展示1:

在这里插入图片描述

下面是示例代码,其中 x 和 y 是十字线交点的坐标,xmin 和 xmax 是 x 轴的范围,ymin 和 ymax 是 y 轴的范围。

import matplotlib.pyplot as plt
import numpy as np
# 十字线交点的坐标
x = 0.5
y = 0.5

# x 轴和 y 轴的范围
xmin = 0
xmax = 1
ymin = 0
ymax = 1

# 创建子图
fig, ax = plt.subplots()

# 绘制十字线
ax.axvline(x=x, color='gray', linestyle='--')
ax.axhline(y=y, color='gray', linestyle='--')

# 填充四个象限的颜色
ax.fill_between([xmin, x], [ymin, ymin], [y, y], color='blue', alpha=0.2)
ax.fill_between([xmin, x], [y, y], [ymax, ymax], color='green', alpha=0.2)
ax.fill_between([x, xmax], [ymin, ymin], [y, y], color='red', alpha=0.2)
ax.fill_between([x, xmax], [y, y], [ymax, ymax], color='yellow', alpha=0.2)

# 设置 x 轴和 y 轴的范围
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
# 添加散点
x = np.random.randn(50)
y = np.random.randn(50)
ax.scatter(x, y, s=20, color='blue')
# 显示图形
plt.show()

运行上述代码后,就可以得到一个分为四个象限的子图,并在其中绘制一条十字线。

结果展示2:

在这里插入图片描述
代码如下:

import matplotlib.pyplot as plt
import numpy as np

# 创建画布和子图对象
fig, ax = plt.subplots(figsize=(6, 6))

# 绘制一条垂直线和一条水平线,形成十字线
ax.axvline(x=0, color='black', linewidth=0.5)
ax.axhline(y=0, color='black', linewidth=0.5)

# 将整个子图分为四个象限
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

# 添加散点
x = np.random.randn(50)
y = np.random.randn(50)
ax.scatter(x, y, s=20, color='blue')

# 设置坐标轴范围
ax.set_xlim(-3, 3)
ax.set_ylim(-3, 3)

# 添加标题和标签
ax.set_title('Scatter Plot with Crosshairs')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')

plt.show()

推荐阅读