9、10、11、12、13_添加标注 (Annotations)、添加网格线(Grid Lines)、显示中文字体、保存图形(saving Figures)、高质量矢量图输出

9.添加标注 (Annotations)
10.添加网格线(Grid Lines)
11.显示中文字体
12.保存图形(saving Figures)
13.高质量矢量图输出

9.添加标注 (Annotations)

有时候我们对某点如3∗sin(3∗pi/4)的值特别感兴趣。

import numpy as np
print(3 * np.sin(3 * np.pi / 4))

2.121320343559643

如果想在图标上标出这一点,可以使用annotate函数执行此操作。

import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-2 * np.pi, 3 * np.pi, 70, endpoint=True)
F1 = np.sin(X)
F2 = 3 * np.sin(X)
ax = plt.gca()
plt.xticks( [-6.28, -3.14, 3.14, 6.28],
        [r'$-2\pi$', r'$-\pi$', r'$+\pi$', r'$+2\pi$'])
plt.yticks([-3, -1, 0, +1, 3])
x = 3 * np.pi / 4
plt.scatter([x,],[3 * np.sin(x),], 50, color ='blue')
plt.annotate(r'$(3\sin(\frac{3\pi}{4}),\frac{3}{\sqrt{2}})$',
         xy=(x, 3 * np.sin(x)),
         xycoords='data',
         xytext=(+20, +20),
         textcoords='offset points',
         fontsize=16,
         arrowprops=dict(facecolor='blue'))
plt.plot(X, F1, label="$sin(x)$")
plt.plot(X, F2, label="$3 sin(x)$")
plt.legend(loc='lower left')
plt.show()

在这里插入图片描述

我们必须提供有关annotate参数的一些信息。

参数含义
xycoordinates of the arrow tip
xytextcoordinates of the text location

我们示例的xy和xytext位置在数据坐标中。 我们还可以选择其他坐标系系统。 可以为xy和xytext的坐标系指定字符串值,赋值给xycoords和textcoords。 默认值为“data”:

字符串值坐标系统
‘figure points’Points from the lower left of the figure
‘figure pixels’Pixels from the lower left of the figure
‘figure fraction’Fraction of figure from lower left
‘axes points’Points from lower left corner of axes
‘axes pixels’Pixels from lower left corner of axes
‘axes fraction’Fraction of axes from lower left
‘data’Use the coordinate system of the object being annotated (default)
‘polar’(theta, r) if not native ‘data’ coordinates

此外,还可以指定箭头的属性。 为此,我们必须为参数arrowprops提供一个箭头属性字典:

arrowprops key描述
widthThe width of the arrow in points
headwidthThe width of the base of the arrow head in points
headlengthThe length of the arrow head in points
shrinkFraction of total length to shrink from both ends
**kwargsany key for matplotlib.patches.Polygon, e.g., facecolor

在以下示例中,我们将更改上一示例的箭头的外观:

import numpy as np
import matplotlib.pyplot as plt

X = np.linspace(-2 * np.pi, 3 * np.pi, 70, endpoint=True)
F1 = np.sin(X)
F2 = 3 * np.sin(X)
ax = plt.gca()
plt.xticks([-6.28, -3.14, 3.14, 6.28],
           [r'$-2\pi$', r'$-\pi$', r'$+\pi$', r'$+2\pi$'])
plt.yticks([-3, -1, 0, +1, 3])
x = 3 * np.pi / 4
plt.scatter([x, ], [3 * np.sin(x), ], 50, color='blue')
plt.annotate(r'$(3\sin(\frac{3\pi}{4}),\frac{3}{\sqrt{2}})$',
             xy=(x, 3 * np.sin(x)),
             xycoords='data',
             xytext=(+20, +20),
             textcoords='offset points',
             fontsize=16,
             arrowprops=dict(facecolor='blue', headwidth=10, headlength=10, width=2, shrink=0.1))
plt.plot(X, F1, label="$sin(x)$")
plt.plot(X, F2, label="$3 sin(x)$")
plt.legend(loc='lower left')
plt.show()

在这里插入图片描述

10.添加网格线(Grid Lines)

import numpy as np
import matplotlib.pyplot as plt


def f(t):
    return np.exp(-t) * np.cos(2 * np.pi * t)


def g(t):
    return np.sin(t) * np.cos(1 / (t + 0.1))


t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.plot(t1, g(t1), 'ro', t2, f(t2), 'k')
plt.grid(color='b', alpha=0.5, linestyle='dashed', linewidth=1.0)
plt.show()

在这里插入图片描述

11.显示中文字体

Matplotlib默认是不支持显示中文字符的。

解决方法: 可以使用 rc 配置(rcParams)来自定义图形的各种默认属性。

Windows操作系统支持的中文字体和代码:
在这里插入图片描述

配置方式:

plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']

示例如下:

import matplotlib.pyplot as plt
# 在jupyter notebook 中,设置下面两行来显示中文
plt.rcParams['font.family'] = ['sans-serif']
# 在 PyCharm 中,只需要下面一行,‘STXingkai’:华文行楷
plt.rcParams['font.sans-serif'] = ['STXingkai']
days = list(range(1,9))
celsius_values = [25.6, 24.1, 26.7, 28.3, 27.5, 30.5, 32.8, 33.1]
plt.plot(days, celsius_values)
plt.xlabel('日期', size=16)
plt.ylabel('摄氏度', size=16)
plt.title('温度变化', size=16)
plt.show()

在这里插入图片描述

另外的方法:
在每一处使用到中文输出的地方,都加上一个字体属性fontproperties

import matplotlib.pyplot as plt
days = list(range(1,9))
celsius_values = [25.6, 24.1, 26.7, 28.3, 27.5, 30.5, 32.8, 33.1]
plt.plot(days, celsius_values)
plt.xlabel('日期', fontproperties='SimHei', size=16)
plt.ylabel('摄氏度', fontproperties='STXingkai', size=16)
plt.title('温度变化', fontproperties='SimHei', size=16)
plt.show()

在这里插入图片描述

12.保存图形(saving Figures)

savefig方法可用来保存图形到文件中:

fig.savefig(“filename.png”)

可以指定分辨率DPI(Dots Per Inch,每英寸点数)和选择输出文件格式:

可以采用PNG,JPG,EPS,SVG,PGF和PDF格式生成输出。

import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([0, 1, 2, 3, 4], [0, 3, 5, 9, 11])
plt.xlabel('Months')
plt.ylabel('Books Read')
plt.show()
fig.savefig('books_read.png')

在这里插入图片描述

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('books_read.png')
plt.imshow(img)

在这里插入图片描述

13.高质量矢量图输出

Jupyter Notebook中显示svg矢量图的设置: %config InlineBackend.figure_format = ‘svg’

%matplotlib inline
%config InlineBackend.figure_format = 'svg'
import matplotlib.pyplot as plt
# 在jupyter notebook 中,设置下面两行来显示中文
plt.rcParams['font.family'] = ['sans-serif']
# 在 PyCharm 中,只需要下面一行 
plt.rcParams['font.sans-serif'] = ['SimHei']
days = list(range(1,9))
celsius_values = [25.6, 24.1, 26.7, 28.3, 27.5, 30.5, 32.8, 33.1]
fig = plt.figure()
plt.plot(days, celsius_values)
plt.xlabel('日期', size=16)
plt.ylabel('摄氏度', size=16)
plt.title('温度变化', size=16)
plt.show()
fig.savefig('celsius_degrees.svg')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

涂作权的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值