Skip to main content
 首页 » 编程设计

python之matplotlib 分离散点图点并创建分割曲线

2024年12月31日8TianFang

我正在尝试在 matplotlib 中的散点图上创建一条除法曲线,它会根据标记大小划分我的散点图。

(x,y) 是 phi0 和 phi0dot,我根据第三个变量“e-folds”着色/调整大小。我想绘制一条“S”形曲线,将绘图分成小的黑色标记和大的青色标记。

Here是一个示例散点图,其中点数很少。最终我将运行数万个数据点,这样分区会更精细,更明显的“S”形。 This大致就是我的想法。

到目前为止,我的代码如下所示:

# Set up the PDF 
pdf_pages = PdfPages(outfile) 
plt.rcParams["font.family"] = "serif" 
 
# Create the canvas 
canvas = plt.figure(figsize=(14.0, 14.0), dpi=100) 
plt.subplot(1, 1, 1) 
 
for a, phi0, phi0dot, efolds in datastore: 
    if efolds[-1] > 65: 
        plt.scatter(phi0[0], phi0dot[0], s=200, color='aqua') 
    else: 
        plt.scatter(phi0[0], phi0dot[0], s=30, color='black') 
 
# Apply labels 
plt.xlabel(r"$\phi_0$") 
plt.ylabel(r"$\dot{\phi}_0$") 
 
# Finish the file 
pdf_pages.savefig(canvas) 
pdf_pages.close() 
print("Finished!") 

This type of separation非常类似于我想做的事情,但不要立即看到我将如何将其扩展到我的问题。任何建议将不胜感激。

请您参考如下方法:

我假设不同分类点之间的分隔线是沿着阈值的简单轮廓线。

这里我假设分类采用 0 的值或 1 , 因此可以画一个 contour沿0.5 ,

ax.contour(x,y,clas, [0.5]) 

例子:

import numpy as np 
import matplotlib.pyplot as plt 
 
# Some data on a grid 
x,y = np.meshgrid(np.arange(20), np.arange(10)) 
z = np.sin(y+1) + 2*np.cos(x/5) + 2 
 
 
fig, ax = plt.subplots() 
 
# Threshold; values above the threshold belong to another class as those below. 
thresh = 2.5 
clas = z > thresh 
size = 100*clas + 30*~clas 
 
# scatter plot 
ax.scatter(x.flatten(), y.flatten(), s = size.flatten(), c=clas.flatten(), cmap="bwr") 
# threshold line 
ax.contour(x,y,clas, [.5], colors="k", linewidths=2) 
 
plt.show()