Python小练习:绘制散点图并添加基线
作者:凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/
1. plot_scatter_test.py
1 # -*- coding: utf-8 -*- 2 # Author:凯鲁嘎吉 Coral Gajic 3 # https://www.cnblogs.com/kailugaji/ 4 # Python绘制散点图 5 import matplotlib.pyplot as plt 6 plt.rc('font',family='Times New Roman') 7 import numpy as np 8 9 def plot_scatter(x, y, baseline, label): 10 min_x, max_x = x.min(), x.max() 11 plt.scatter(x, y, 12 s = 5, # 点的大小 13 color = 'red', 14 marker='.', # 默认'o' 15 label = label) 16 print('------绘制散点图', label, '------') 17 # 绘制额外的虚线baseline 18 if baseline == 'no': 19 pass 20 elif baseline == 'y=x': 21 plt.plot([min_x, max_x], [min_x, max_x], # x: [min_x, max_x], y: [min_x, max_x] 22 color = 'gray', 23 ls = '--', 24 label = baseline, 25 alpha = 0.3) 26 elif baseline == 'y=0': 27 plt.plot([min_x, max_x], [0, 0], # x: [min_x, max_x], y: [0, 0] 28 color = 'gray', 29 ls = '--', 30 label = baseline, 31 alpha = 0.3) 32 else: 33 raise NotImplementedError 34 print('------绘制基准线', baseline, '------') 35 plt.grid(ls='--') 36 37 x = np.linspace(-1, 1, 150, endpoint=True) 38 y = np.sin(x) 39 label = 'y=sin(x)' 40 baseline = 'y=x' 41 plot_scatter(x, y, baseline, label) 42 # 添加x轴和y轴标签 43 plt.xlabel('x') 44 plt.ylabel('y') 45 plt.legend() 46 plt.savefig('Scatter Diagram.png', bbox_inches='tight', dpi=600) 47 plt.show()
2. 结果
D:\ProgramData\Anaconda3\python.exe "D:/Python code/2023.3 exercise/Scatter/plot_scatter_test.py" ------绘制散点图 y=sin(x) ------ ------绘制基准线 y=x ------ Process finished with exit code 0标签:plt,baseline,min,Python,max,散点图,label,基线,------ From: https://www.cnblogs.com/kailugaji/p/17246645.html