1.使用pyplot模块画图。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 1000)
y = np.sin(x)
z = np.cos(x**2)
plt.figure(figsize=(8, 5))
plt.plot(x, y, label="$sin(x)$", color="red", linewidth=2)
#label可以使用内嵌Latex引擎,color可以用0到1范围内三个元素的元组表示(1.0,0.0,0.0)也表示红色,linwidth:指定曲线的宽度,可以不是整数,也可以缩写为1w.
plt.plot(x, z, "b--",label = "$cos(x^2)$")
plt.xlabel("Time(s)")
plt.ylabel("Volt")
'''
xlim()、ylim()分别表示x,y轴的显示范围
'''
plt.title("PyPlot First Example")
plt.legend()#显示图示,图中每条曲线的标签所在的矩形区域,loc参数可调整位置。
plt.savefig("c:\\figure1.png")
2.用subplot()绘制多个子图。
import matplotlib.pyplot as plt
plt.subplot(221) #分成2x2,占用第一个,即第一行第一列的子图
plt.subplot(222)#分成2x2,占用第二个,即第一行第二列的子图
plt.subplot(212)#分成2x1,占用第二个,即第二行
plt.show()
import matplotlib.pyplot as plt
for idx,color in enumerate('rgbyck'):
plt.subplot(321+idx, axisbg=color)
plt.savefig("c:\\figure1.png")
3.显示中文字体:
首先获取配置文件的绝对路径;
from os import path
path.abspath(matplotlib.matplotlib_fname())
然后打开matplotlibrc文件,
修改如下:
font.family : Microsoft YaHei
font.sans-serif : Microsoft YaHei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
修改的项去掉前面的#
最后重新导入配置文件:
import matplotlib
matplotlib.pyplot.rcdefaults() #matplotlib载入时从配置文件读入的配置
matplotlib.rcParams.update(matplotlib.rc_params()) #重新从配置文件载入最新的配置
另外也可以直接在程序中修改:
plt.rcParams[“font.family”]=”SimHei”
4.坐标变换和注释
# -*- coding: utf-8 -*-
__author__ = 'zzw'
import numpy as np
from matplotlib import pyplot as plt
def func1(x) :
return 0.6*x+0.3
def func2 (x):
return 0.4*x*x + 0.1 *x+0.2
def find_cure_intersects(x, y1, y2): #计算两条曲线的交点
d = y1-y2
idx = np.where(d[:-1]*d[1:]<=0)[0]
x1, x2 = x[idx], x[idx+1]
d1, d2 = d[idx], d[idx+1]
return -d1*(x2-x1)/(d2-d1) + x1
x = np.linspace(-3, 3, 100)
f1 = func1(x)
f2 = func2(x)
fig, ax = plt.subplots(figsize=(8,4))
ax.plot(x, f1)
ax.plot(x, f2)
x1, x2 = find_cure_intersects(x, f1, f2)
ax.plot(x1, func1(x1), "o")
ax.plot(x2, func1(x2), "o")
ax.fill_between(x, f1, f2, where=f1 > f2, facecolor="green", alpha=0.5)
from matplotlib import transforms
trans = transforms.blended_transform_factory(ax.transData, ax.transAxes)
ax.fill_between([x1, x2], 0, 1, transform=trans, alpha = 0.1)
a =ax.text(0.05, 0.95, u"直线和二次曲线的交点",
transform=ax.transAxes,
verticalalignment = "top",
fontsize = 18,
bbox={
"facecolor":"red", "alpha":0.4, "pad":10})
arrow = {
"arrowstyle"</