python文本&注释&数学表达式设置|python绘图中的数学表达式设置

本篇文章将介绍如何在Matplotlib中设置文本、注释和数学表达式,以便更好地呈现数据,提高可视化效果。



一、Matplotlib中的文本设置

1.1 纯文本设置

提示:这里可以添加本文要记录的大概内容:

可以通过text()函数来添加文本。text()函数的语法格式如下:

text(x, y, s, fontdict=None, withdash=False, **kwargs)
  1. x和y表示文本的横纵坐标,
  2. s表示要添加的文本内容,
  3. fontdict表示字体属性的字典,
  4. withdash表示是否使用虚线框选文本,
  5. kwargs为可选参数。
    可以通过以下代码在Matplotlib中添加文本
import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [4, 5, 6]

plt.plot(x, y)

plt.text(2, 5, "This is a text", fontsize=12, color="red")

plt.show()

在这里插入图片描述
首先使用plot()函数绘制了一条直线,然后使用text()函数在坐标点(2,5)处添加了一段文本,字体大小为12,颜色为红色。

1.2 含箭头的文本设置

除了text()函数外,我们还可以使用annotate()函数来添加注释。它的语法格式如下:

annotate(s, xy, xytext=None, xycoords='data', 
	textcoords='offset points', arrowprops=None, **kwargs)
  1. s表示要添加的文本内容,
  2. xy表示箭头指向的坐标点,
  3. xytext表示文本的坐标点,默认为None,表示使用与xy相同的坐标点,
  4. xycoords和textcoords分别表示xy和xytext的坐标系,默认为"data",表示数据坐标系,
  5. arrowprops表示箭头的属性,kwargs为可选参数。
import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [4, 5, 6]

plt.plot(x, y)

plt.annotate("This is an annotation", xy=(2, 5), xytext=(2.5, 5.5), 
             arrowprops=dict(facecolor='red', shrink=0.05), fontsize=12)

plt.show()

在这里插入图片描述


二、Matplotlib中的数学表达式设置

还可以使用数学表达式来添加文本或注释,用于呈现数学公式等内容。Matplotlib支持的数学表达式语法类似于LaTeX,可以让我们方便地添加各种常见的数学符号和函数。
我们可以在文本中使用两种模式的数学表达式:行内模式和行间模式。行内模式使用单个美元符号$包围数学表达式,例如:

import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [4, 5, 6]
plt.plot(x, y)
plt.text(2, 5, r"$y = \sqrt{x}$", fontsize=12)
plt.show()

在这里插入图片描述


文本中使用了数学表达式,其中使用了\sqrt{x}表示求根号的操作。
与之对应的,行间模式使用一对$$符号包围数学表达式,例如:

import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [4, 5, 6]

plt.plot(x, y)

plt.annotate(r"$\sum_{i=1}^n i = \frac{n(n+1)}{2}$", 
xy=(2, 5), xytext=(2.5, 5.5), 
arrowprops=dict(facecolor='red', shrink=0.05), fontsize=12)
plt.show()

在这里插入图片描述

三、Matplotlib中的字体设置

在Matplotlib中,我们还可以通过fontdict参数来设置文本或注释的字体属性,包括字体大小、颜色、字体类型等。fontdict参数是一个字典,其中包含了各种字体属性的键值对。

import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [4, 5, 6]

plt.plot(x, y)

font = {
    
    'family': 'Times New Roman',
         'color':  'darkred',
         'weight': 'normal',
         'size': 14,
         }

plt.text(2, 5, "This is a text", fontdict=font)

plt.show()

猜你喜欢

转载自blog.csdn.net/m0_58857684/article/details/131036793