Python 绘图

常用的 Python 绘图工具是 Matplotlib

折线图

使用 plot 函数在 Matplotlib 中创建折线图:

import matplotlib.pyplot as plt

# 数据
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

# 创建折线图
plt.plot(x, y, marker='o', linestyle='-', color='b', label='Line 1')
# 设置标题和标签
plt.title('Simple Line Plot')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.legend()
# 显示图形
plt.show()

image

散点图

使用 scatter 函数在 Matplotlib 中创建散点图:

import matplotlib.pyplot as plt

# 数据
x_train = [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0]
y_train = [300.0, 400.0, 500.0, 550.0, 650.0, 750.0, 800.0]

# 创建散点图
plt.scatter(x_train, y_train, marker='x', c='r')
# 设置标题和标签
plt.title("Housing Prices")
plt.xlabel('Size (1000 sqft)')
plt.ylabel('Price (in 1000s of dollars)')
# 显示图形
plt.show()

image

设置字体

  • 为每个元素单独设置字体:

    import matplotlib.pyplot as plt
    
    times = {'fontname':'Times New Roman'}  # Times New Roman
    cmmi10 = {'fontname':'cmmi10'}          # Computer Modern Math Italic
    
    plt.title('title',**times)              # 设置标题使用 Times New Roman
    plt.xlabel('xlabel', **cmmi10)          # 设置 X 轴标签使用 Computer Modern Math Italic
    
  • 设置全局字体:

    import matplotlib.pyplot as plt
    
    # 设置正文字体栈为 ['Times New Roman', 'SimSun']
    plt.rcParams['font.family'] = ['Times New Roman', 'SimSun']
    # 设置数学字体为 STIX
    plt.rcParams['mathtext.fontset'] = 'stix'
    

数学公式

可以通过启用 TeX 选项来显示 LaTeX 公式(需要电脑已安装 TeX Live):

import matplotlib.pyplot as plt
import numpy as np

# 启用 LaTeX 风格
plt.rcParams['text.usetex'] = True

x = np.linspace(0, 10, 1000)
y = np.sin(x**2) * np.exp(-x/3) + 0.5 * np.cos(3*x) / (1 + x)

# 显示图形
plt.plot(x, y)
plt.title(r'$\sin(x^2)e^{-x/3} + \frac{1}{2}\frac{\cos(3x)}{1+x}$')
plt.xlabel(r'$x$')
plt.ylabel(r'$\sin(x^2)e^{-x/3} + \frac{1}{2}\frac{\cos(3x)}{1+x}$')
plt.show()

image

参考:How to change fonts in matplotlib (python)? | Stack Overflow

如果需要同时显示数学公式和中文字体,需要配置 XeLaTeX 包:

import matplotlib.pyplot as plt
import matplotlib
import numpy as np

# 使用 pgf 后端(XeLaTeX)
matplotlib.use('pgf')

plt.rcParams['pgf.preamble'] = '\n'.join([
    r'\usepackage{xeCJK}',
    r'\setCJKmainfont{SimSun}'
])

# 生成数据点
x = np.linspace(-5, 5, 1000)
y = x**2 * np.exp(-x**2/4)

# 绘制函数曲线
plt.figure(figsize=(8, 6))
plt.plot(x, y, 'b-', label=r'$f(x)=x^2e^{-x^2/4}$')
plt.grid(True, alpha=0.3)
plt.title(r'高斯型二次函数曲线 $f(x)=x^2e^{-x^2/4}$')
plt.xlabel(r'$x$')
plt.ylabel(r'$f(x)$')
plt.legend(loc='best')
plt.tight_layout()

# 保存为 PDF 文件
plt.savefig('figure.pdf')

使用了 XeLaTeX 的缺点是无法交互式地显示图像,只能打印图像。并且只能打印 PDF 而不能打印 SVG。

保存图像

  • 矢量图

    # 保存为 SVG 格式
    plt.savefig('plot.svg')
    
    # 保存为 PDF 格式
    plt.savefig('plot.pdf')
    
    # 保存为 EPS 格式
    plt.savefig('plot.eps')
    
    • SVG 适合在网页上显示图像
    • PDF 适合用于文档
    • EPS 适合高质量印刷
  • 位图

    plt.savefig('plot.png', dpi=300)
    

更多示例

折线图

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.family'] = ['Times New Roman', 'SimSun'] # 设置字体族
plt.rcParams['axes.unicode_minus'] = False # 显示负号

x = np.array([3,5,7,9,11,13,15,17,19,21])

A = np.array([0.9708, 0.6429, 1, 0.8333, 0.8841, 0.5867, 0.9352, 0.8000, 0.9359, 0.9405])
B = np.array([0.9708, 0.6558, 1, 0.8095, 0.8913, 0.5950, 0.9352, 0.8000, 0.9359, 0.9419])
C = np.array([0.9657, 0.6688, 0.9855, 0.7881, 0.8667, 0.5952, 0.9361, 0.7848, 0.9244, 0.9221])
D = np.array([0.9664, 0.6701, 0.9884, 0.7929, 0.8790, 0.6072, 0.9352, 0.7920, 0.9170, 0.9254])

# label 在图示(legend)中显示。若为数学公式,则最好在字符串前后添加 $ 符号
# color: b:blue, g:green, r:red, c:cyan, m:magenta, y:yellow, k:black, w:white
# 线型:- -- -. : ,
# marker: . , o v < * + 1

plt.figure(figsize=(10,5))
plt.grid(linestyle="--") # 设置背景网格线为虚线
ax = plt.gca()

ax.spines['top'].set_visible(False) # 去掉上边框
ax.spines['right'].set_visible(False) # 去掉右边框

# A 图
plt.plot(x, A, color="black", label="A algorithm", linewidth=1.5)
# B 图
plt.plot(x, B, "k--", label="B algorithm", linewidth=1.5)
# C 图
plt.plot(x, C, color="red", label="C algorithm", linewidth=1.5)
# D 图
plt.plot(x, D, "r--", label="D algorithm", linewidth=1.5)

# 设置标题
plt.title("example", fontsize=12, fontweight='bold')

# 设置坐标轴刻度标识
x_ticks=['dataset1', 'dataset2', 'dataset3', 'dataset4', 'dataset5', ' dataset6', 'dataset7', 'dataset8', 'dataset9', 'dataset10'] # X 轴刻度的标识
plt.xticks(x, x_ticks, fontsize=12, fontweight='bold')
plt.yticks(fontsize=12, fontweight='bold')

# 设置坐标轴标签
plt.xlabel("Data sets", fontsize=13, fontweight='bold')
plt.ylabel("Accuracy", fontsize=13, fontweight='bold')

# 设置坐标轴范围
plt.xlim(3,21)
# plt.ylim(0.5,1)

# 显示图例
# plt.legend()
plt.legend(loc=0, numpoints=1)
leg = plt.gca().get_legend()
ltext = leg.get_texts()
plt.setp(ltext, fontsize=12, fontweight='bold') # 设置图例字体的大小和粗细

plt.savefig('filename.svg') # 建议保存为 svg 格式,再用 inkscape 转为矢量图 emf 后插入 word 中
plt.show()

image

参考:画论文折线图、曲线图?几个代码模板轻松搞定!

posted @ 2024-06-07 15:22  Undefined443  阅读(10)  评论(0编辑  收藏  举报