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":"fancy,tail_width=0.6",
"facecolor":"gray",
"connectionstyle":"arc3,rad=-0.3"}
ax.annotate(u"交点",
xy=(x1, func1(x1)),xycoords="data",
xytext=(0.05, 0.5), textcoords="axes fraction",
arrowprops = arrow)
ax.annotate(u"交点",
xy=(x1, func1(x2)),xycoords="data",
xytext=(0.05, 0.5), textcoords="axes fraction",
arrowprops = arrow)
'''所有注释箭头坐标都采用data,因此无论放大或者平移绘图区域,箭头始终指向数据坐标系中的固定点。而注释文本的“交点”坐标变换采用axes fraction因此焦点始终保持在子图的固定位置。而"直线大于去曲线区域"注释文本的坐标采用“offset point”,因此文字和箭头的相对位置始终保持不变'''
xm = (x1+x2)/2
ym = (func1(xm) - func2(xm))/2+func2(xm)
o = ax.annotate(u"直线大于曲线区域",
xy = (xm,ym),xycoords="data",
xytext = (30,-30), textcoords="offset points",
bbox={"boxstyle":"round","facecolor":(1.0, 0.7, 0.7),"edgecolor":"none"},
fontsize=16,
arrowprops={"arrowstyle":"->"}
)#添加箭头,s是注释的文本,xy是箭头所指处的坐标,xytext是注释文本所在的坐标,xycoords和textcoords都是字符串
plt.savefig("C:\\figure1.png")
属性值 | 坐标变换方式 |
figure fraction | 使用图标坐标系 |
axes fraction | 使用子图坐标系 |
data | 使用数据坐标系 |
5添加阴影
# -*- coding: utf-8 -*-
__author__ = 'zzw'
from matplotlib import pyplot as plt
import numpy as np
from matplotlib import transforms
fig, ax = plt.subplots()
x = np.arange(0., 2., 0.01)
y = np.sin(2*np.pi*x)
N = 7
for i in xrange(N, 0, -1):
offset = transforms.ScaledTranslation(i, -i, transforms.IdentityTransform())
#offset前两个参数决定了x和y轴的偏移量,第三个参数是一个坐标变换对象,经过他变换后,在进行便宜变换,由于程序中是一个恒等变换,所以offset
#仅仅是一个便宜变换,x轴+i,y轴-i
shadow_trans = ax.transData + offset
'''
ax.transData.transform((0,0)) #对(0,0)进行数据坐标变换[60,120]
shadow_trans.transform((0,0))#对(0,0)进行数据坐标变换和便宜变换[61,119]
有与shadow_trans是先完成数据坐标到窗口坐标的变换之后,在进行便宜变换,一次无论当前的缩放比例如何,阴影都有
'''
ax.plot(x,y,linewidth=4, color="black",
transform = shadow_trans,
alpha = (N-i)/2.0/N)
ax.plot(x, y, linewidth=4, color='black')
ax.set_ylim((-1.5, 1.5))
#plt.show()
plt.savefig("c:\\figure1.png")
6.添加注释
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-1,1,10)
y=x**2
fig, ax = plt.subplots(figsize=(8,4))
ax.plot(x, y)
for i, (_x, _y) in enumerate(zip(x, y)):
ax.text(_x, _y, str(i), color="red", fontsize=i+10)
ax.text(0.6, 0.8, u"子图坐标系中的文字", color="blue", ha="center",transform=ax.transAxes)
plt.figtext(0.1, 0.92, u"图表坐标系中的文字", color='green')
plt.show()
7.柱状图
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt("C:\\china_population.txt")
print data[1, 0],data[0,0]
width = (data[1, 0] - data[0, 0])*0.4#每个年龄段显示两次
plt.figure(figsize=(8,5))
plt.bar(data[:, 0]-width, data[:, 1]/1e7, width, color="b", label=u"男")
#第一个参数是每根柱子左边缘的横坐标,第二个参数是每根柱子的高度,第三个参数式所有柱子的宽度,当第三个柱子为序列时可以指定每根柱子的宽度。
plt.bar(data[:, 0], data[:,2]/1e7, width, color="r", label=u"女")
plt.xlim(-width, 100)
plt.xlabel(u"年龄")
plt.ylabel(u"人口(千万)")
plt.legend()
plt.show()
8.散列图
import numpy as np
import matplotlib.pyplot as plt
x = np.random.random(100)
y = np.random.random(100)
plt.scatter(x, y, s=x*1000, c=y, marker=(5, 1), alpha=0.8, lw=2, facecolors="none")
'''
scatter()的前两个参数是两个数组,分别指定每个点的x,y轴坐标,s参数指定点的大小可以是单个数值或数组,c指定每个点的颜色,蓝色与最小值对应红色最大对应。当c参数的形状是(N,3)或(N,4)的二维数组时,则直接表示每个点的RGB颜色。
maker设置点的形状,第一个是多边形的变数,第二个是多边形的样式,0表示多边形,1表示星型,2表示放射型,3表示圆形。
alpha设置透明度
lw线宽
facecolors为None表示散列点没有填充颜色。
'''
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.savefig("c:\\figure1.png")
9.图像:
imread()和imshow()提供了简单的图像载入和显示功能,得到一个表示图像的numpy数组,对于灰度图像是二维的(M,N),对于彩色图像是三维的(M,N,C)c表示通道数(R,G,B)
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
plt.subplots_adjust(0,0,1,1,0.05,0.05)
plt.subplot(331)
img = plt.imread("C:\\lena.jpg")
plt.imshow(img)
plt.subplot(332)
plt.imshow(img[::-1]) #图像上下颠倒
plt.subplot(333)
plt.imshow(img, origin="lower") #图像上下颠倒
img = img[::-1]
plt.subplot(334)
plt.imshow(img*1.0) #如果为浮点数则范围是(0.1~1.0)与颜色值0~255对应,超过会出现异常
plt.subplot(335)
plt.imshow(img/255.0)
plt.subplot(336)
plt.imshow(np.clip(img/200.0, 0, 1)) #使用clip将范围限制,可以使图片变亮
plt.subplot(325)
plt.imshow(img[:,:,0])#显示图像中的红色通道
plt.colorbar()#颜色映射,最小是蓝色最大为红色
plt.subplot(326)
plt.imshow(img[:,:,0], cmap=cm.copper) #camp可以修改颜色映射表
plt.colorbar()
for ax in plt.gcf().axes: #去掉坐标
ax.set_axis_off()
ax.set_axis_off()
plt.savefig("c:\\figure1.png")
10.隐函数
import numpy as np
import matplotlib.pyplot as plt
y, x = np.ogrid[-1.5:1.5:200j, -1.5:1.5:200j]
f = (x**2 + y**2)**4 - (x**2 - y**2)**2
plt.figure(figsize=(9,4))
plt.subplot(121)
extent = [np.min(x), np.max(x), np.min(y), np.max(y)]
cs = plt.contour(f, extent=extent, levels=[0, 0.1],
colors=["b", "r"], linestyles=["solid", "dashed"], linewidths=[2, 2])
plt.subplot(122)
for c in cs.collections:
data = c.get_paths()[0].vertices
plt.plot(data[:,0], data[:,1],
color=c.get_color()[0], linewidth=c.get_linewidth()[0])
plt.show()
11.箭头图
import numpy as np
import matplotlib.pyplot as plt
def f(x, y):
return x * np.exp(-x**2-y**2)
def vec_filed(f, x, y, dx=1e-6, dy = 1e-6):
x2 = x + dx
y2 = y + dy
v = f(x, y)
vx = (f(x2, y) - v)/dx
vy = (f(x, y2) - v)/dy
return vx, vy #金时计算导数
X, Y = np.mgrid[-2:2:20j, -2:2:20j]
C = f(X, Y)
U, V = vec_filed(f, X, Y)
plt.quiver(X, Y, U, V, C)
#X,Y是箭头起点的坐标,U,V是箭头方向和大小矢量,C是箭头对应的值
plt.colorbar()
plt.gca().set_aspect("equal")
plt.show()
import numpy as np
import matplotlib.pyplot as plt
levels = [4, 5, 3, 2]
x = np.linspace(0, 1, len(levels))
for i in range(len(levels) - 1):
j = i+1
n1, n2 = levels[i], levels[j]
y1, y2 = np.mgrid[0:1:n1*1j, 0:1:n2*1j]
x1 = np.full_like(y1, x[i])
x2 = np.full_like(y2, x[j])
plt.quiver(x1, y1, x2-x1, y2-y1,
angles = "xy", units = "dots", scale_units = "xy",
scale = 1, width = 2, headlength = 10,
headaxislength=10, headwidth=4)
yp = np.concatenate([np.linspace(0, 1, n) for n in levels])
xp = np.repeat(x, levels)
plt.plot(xp,yp,"o", ms = 12)
plt.gca().axis("off")
plt.margins(0.1, 0.1)
plt.show()
12.高亮显示
import numpy as np
import matplotlib.pyplot as plt
class CurveHighLighter(object):
def __init__(self, ax, alpha=0.3, linewidth=3):
self.ax = ax
self.alpha = alpha
self.linewidth = linewidth
ax.figure.canvas.mpl_connect('motion_notify_event', self.on_move)
#绑定鼠标移动事件motion_notify_event到on_move()上,当鼠标移动时会调用on_move()方法
def highlight(self, target):# target表示高亮显示的Line2D对象,如果为None表示取消高亮显示
need_redraw = False
if target is None:
for line in self.ax.lines:
line.set_alpha(1.0) #无高亮时所有曲线的alpha属性和linewidth设置为1
if line.get_linewidth()!=1.0:
line.set_linewidth(1.0)
need_redraw = True
else:
for line in self.ax.lines:
lw = self.linewidth if line is target else 1 #有高亮时alpha设置为1,lw设置为3,非高亮的alpha设置为0.3linewidth设置为1
if line.get_linewidth()!=lw:
line.set_linewidth(lw)
need_redraw=True
alpha = 1.0 if lw == self.linewidth else self.alpha
line.set_alpha(alpha)
if need_redraw:
self.ax.figure.canvas.draw_idle() #有任何一条被修改会重新画图
def on_move(self, evt):
ax = self.ax
for line in ax.lines:
if line.contains(evt)[0]:
self.highlight(line)
break
else:
self.highlight(None)
fig, ax = plt.subplots()
x = np.linspace(0, 50, 300)
from scipy.special import jn
for i in range(1, 10):
ax.plot(x, jn(i, x))
ch = CurveHighLighter(ax)
plt.show()
plt.savefig("c:\\figure1.png")
13.修改x轴和y轴
__author__ = 'zzw'
from pylab import *
import matplotlib.pyplot as pyplot
x=[1,2,3,4,5,6,7]
a = [ 0.3, 0.48, 1, 1.75, 2.3, 2.85, 3.65]#LList
b = [0.35, 0.78, 1.8, 3.2, 4.3, 4.9, 5.3]#Acyclic-idle-slot
fig = pyplot.figure()
ax = fig.add_subplot(1, 1, 1)
group_labels = ['4','8','16','32','64','128','256']
ax.plot(x,a, 'rs--', label="Acyclic-idle-slot", lw=1.5)
ax.plot(x,b, 'bh-', label="LList")
plt.xticks(x, group_labels, rotation=0)
ax.legend(loc='upper left', numpoints=1)
ax.set_xlabel('Number of harmonic tasks per taskset')
ax.set_ylabel('Average running time per taskset(ms)')
#ax.set_xscale('log')
ax.yaxis.grid(True)
#show()
savefig("C:\\qg.png")
# -*- coding: utf-8 -*-
__author__ = 'zzw'
from pylab import *
import matplotlib.pyplot as pyplot
a = [0, 0, 0, 0.075, 0.070, 0.09, 0.098, 0.19, 0.11, 0.23]
b = [0, 0, 0, 0.75, 7.5, 40, 300, 700, 5500, 10001]
fig = pyplot.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(a, 'rs--', label="Acyclic-idle-slot", lw=1.5)
ax.plot(b, 'bh-', label="LList")
ax.legend(loc='upper left', numpoints=1)
ax.set_xlabel('Number of tasks per taskset')
ax.set_ylabel('Average running time per taskset(ms)')
ax.set_yscale('log')
ax.set_xlim(3, 9.5)
ax.yaxis.grid(True)
#show()
savefig("C:\\qg.png")