python 隐函数绘制_matplotlib画图实例:pyplot、pylab模块及作图參数

Matplotlib.pyplot画图实例

{使用pyplot模块}

matplotlib绘制直线、条形/矩形区域importnumpy asnp

importmatplotlib.pyplot asplt

t =np.arange(-1, 2, .01)

s =np.sin(2*np.pi *t)

plt.plot(t,s)

# draw a thick red hline at y=0 that spans the xrangel =plt.axhline(linewidth=4, color='r')

plt.axis([-1, 2, -1, 2])

plt.show()

plt.close()

# draw a default hline at y=1 that spans the xrangeplt.plot(t,s)

l =plt.axhline(y=1, color='b')

plt.axis([-1, 2, -1, 2])

plt.show()

plt.close()

# draw a thick blue vline at x=0 that spans the upper quadrant of the yrangeplt.plot(t,s)

l =plt.axvline(x=0, ymin=0, linewidth=4, color='b')

plt.axis([-1, 2, -1, 2])

plt.show()

plt.close()

# draw a default hline at y=.5 that spans the the middle half of the axesplt.plot(t,s)

l =plt.axhline(y=.5, xmin=0.25, xmax=0.75)

plt.axis([-1, 2, -1, 2])

plt.show()

plt.close()

plt.plot(t,s)

p =plt.axhspan(0.25, 0.75, facecolor='0.5', alpha=0.5)

p =plt.axvspan(1.25, 1.55, facecolor='g', alpha=0.5)

plt.axis([-1, 2, -1, 2])

plt.show()效果图展示

Note: 设置直线相应位置的值显示:plt.text(max_x, 0, str(round(max_x, 2)))。也就是直接在指定坐标写文字。不知道有没有其他方法?

另一种绘制直线的方式plt.hlines(hline, xmin=plt.gca().get_xlim()[0], xmax=plt.gca().get_xlim()[1], linestyles=line_style, colors=color)

直方图

plt.hist(songs_plays, bins=50,range=(0, 50000), color='lightblue',normed=True)

Note: normed是将y坐标按比例画图,而不是数目。

hist转换成plot折线图

plt.hist直接绘制数据是hist图

plt.hist(z, bins=500, normed=True)hist图转换成折线图cnts, bins =np.histogram(z, bins=500, normed=True)

bins =(bins[:-1] +bins[1:]) /2plt.plot(bins, cnts)

[numpy教程 - 统计函数:histogram]

散点图、梯形图、柱状图、填充图

散列图scatter()

使用plot()画图时。假设指定样式參数为仅绘制数据点,那么所绘制的就是一幅散列图。可是这样的方法所绘制的点无法单独指定颜色和大小。

scatter()所绘制的散列图却能够指定每一个点的颜色和大小。

scatter()的前两个參数是数组,分别指定每一个点的X轴和Y轴的坐标。

s參数指定点的大 小。值和点的面积成正比。它能够是一个数,指定全部点的大小;也能够是数组。分别对每一个点指定大小。

c參数指定每一个点的颜色。能够是数值或数组。这里使用一维数组为每一个点指定了一个数值。

通过颜色映射表,每一个数值都会与一个颜色相相应。

默认的颜色映射表中蓝色与最小值相应,红色与最大值相应。当c參数是形状为(N,3)或(N,4)的二维数组时。则直接表示每一个点的RGB颜色。

marker參数设置点的形状,能够是个表示形状的字符串,也能够是表示多边形的两个元素的元组。第一个元素表示多边形的边数。第二个元素表示多边形的样式,取值范围为0、1、2、3。0表示多边形,1表示星形,2表示放射形。3表示忽略边数而显示为圆形。

alpha參数设置点的透明度。

lw參数设置线宽,lw是line width的缩写。

facecolors參数为“none”时,表示散列点没有填充色。

柱状图bar()

用每根柱子的长度表示值的大小,它们通经常使用来比較两组或多组值。

bar()的第一个參数为每根柱子左边缘的横坐标;第二个參数为每根柱子的高度;第三个參数指定全部柱子的宽度,当第三个參数为序列时,能够为每根柱子指定宽度。bar()不自己主动改动颜色。

n = np.array([0,1,2,3,4,5])

x= np.linspace(-0.75, 1., 100)

fig, axes= plt.subplots(1, 4, figsize=(12,3))

axes[0].scatter(x, x+ 0.25*np.random.randn(len(x)))

axes[1].step(n, n**2, lw=2)

axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5)

axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5);

Note: axes子图设置title: axes.set_title("bar plot")

散点图(改变颜色,大小)

import numpy as np import matplotlib.pyplot as plt

N = 50

x = np.random.rand(N)

y = np.random.rand(N)

area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses

color = 2 * np.pi * np.random.rand(N)

plt.scatter(x, y, s=area, c=color, alpha=0.5, cmap=plt.cm.hsv)

plt.show()

matplotlib绘制散点图给点加上凝视

plt.scatter(data_arr[:, 0], data_arr[:, 1], c=class_labels)

for i, class_label in enumerate(class_labels):

plt.annotate(class_label, (data_arr[:, 0][i], data_arr[:, 1][i]))[matplotlib scatter plot with different text at each data point]

对数坐标图

plot()所绘制图表的X-Y轴坐标都是算术坐标。

绘制对数坐标图的函数有三个:semilogx()、semilogy()和loglog(),它们分别绘制X轴为对数坐标、Y轴为对数坐标以及两个轴都为对数坐标时的图表。

以下的程序使用4种不同的坐标系绘制低通滤波器的频率响应曲线。

当中,左上图为plot()绘制的算术坐标系。右上图为semilogx()绘制的X轴对数坐标系,左下图 为semilogy()绘制的Y轴对数坐标系。右下图为loglog()绘制的双对数坐标系。使用双对数坐标系表示的频率响应曲线通常被称为波特图。

import numpy as np

import matplotlib.pyplot as plt

w = np.linspace(0.1, 1000, 1000)

p = np.abs(1/(1+0.1j*w)) # 计算低通滤波器的频率响应

plt.subplot(221)

plt.plot(w, p, linewidth=2)

plt.ylim(0,1.5)

plt.subplot(222)

plt.semilogx(w, p, linewidth=2)

plt.ylim(0,1.5)

plt.subplot(223)

plt.semilogy(w, p, linewidth=2)

plt.ylim(0,1.5)

plt.subplot(224)

plt.loglog(w, p, linewidth=2)

plt.ylim(0,1.5)

plt.show()

极坐标图

极坐标系是和笛卡尔(X-Y)坐标系全然不同的坐标系,极坐标系中的点由一个夹角和一段相对中心点的距离来表示。polar(theta, r, **kwargs)

能够polar()直接创建极坐标子图并在当中绘制曲线。也能够使用程序中调用subplot()创建子图时通过设 polar參数为True,创建一个极坐标子图,然后调用plot()在极坐标子图中画图。

演示样例1

fig = plt.figure()

ax = fig.add_axes([0.0, 0.0, .6, .6], polar=True)

t = linspace(0, 2 * pi, 100)

ax.plot(t, t, color='blue', lw=3);

演示样例2

import numpy as np

import matplotlib.pyplot as plt

theta = np.arange(0, 2*np.pi, 0.02)

plt.subplot(121, polar=True)

plt.plot(theta, 1.6*np.ones_like(theta), linewidth=2) #绘制同心圆

plt.plot(3*theta, theta/3, "--", linewidth=2)

plt.subplot(122, polar=True)

plt.plot(theta, 1.4*np.cos(5*theta), "--", linewidth=2)

plt.plot(theta, 1.8*np.cos(4*theta), linewidth=2)

plt.rgrids(np.arange(0.5, 2, 0.5), angle=45)

plt.thetagrids([0, 45])

plt.show()

Note:rgrids()设置同心圆栅格的半径大小和文字标注的角度。因此右图中的虚线圆圈有三个。 半径分别为0.5、1.0和1.5,这些文字沿着45°线排列。

Thetagrids()设置放射线栅格的角度, 因此右图中仅仅有两条放射线,角度分别为0°和45°。

等值线图

使用等值线图表示二元函数z=f(x,y)

所谓等值线,是指由函数值相等的各点连成的平滑曲线。等值线能够直观地表示二元函数值的变化趋势,比如等值线密集的地方表示函数值在此处的变化较大。

matplotlib中能够使用contour()和contourf()描绘等值线,它们的差别是:contourf()所得到的是带填充效果的等值线。

import numpy as np

import matplotlib.pyplot as plt

y, x = np.ogrid[-2:2:200j, -3:3:300j]

z = x * np.exp( - x**2 - y**2)

extent = [np.min(x), np.max(x), np.min(y), np.max(y)]

plt.figure(figsize=(10,4))

plt.subplot(121)

cs = plt.contour(z, 10, extent=extent)

plt.clabel(cs)

plt.subplot(122)

plt.contourf(x.reshape(-1), y.reshape(-1), z, 20)

plt.show()

为了更淸楚地区分X轴和Y轴。这里让它们的取值范围和等分次数均不相同.这样得 到的数组z的形状为(200, 300),它的第0轴相应Y轴、第1轴相应X轴。

调用contour()绘制数组z的等值线图,第二个參数为10,表示将整个函数的取值范围等分为10个区间,即显示的等值线图中将有9条等值线。能够使用extent參数指定等值线图的X轴和Y轴的数据范围。

contour()所返回的是一个QuadContourSet对象, 将它传递给clabel(),为当中的等值线标上相应的值。

调用contourf(),绘制将取值范围等分为20份、带填充效果的等值线图。

这里演示了第二种设置X、Y轴取值范围的方法,它的前两个參数各自是计算数组z时所使用的X轴和Y轴上的取样点,这两个数组必须是一维的。

使用等值线绘制隐函数f(x,y)=0曲线

显然,无法像绘制一般函数那样,先创建一个等差数组表示变量的取值点。然后计算出数组中每一个x所相应的y值。

能够使用等值线解决问题,显然隐函数的曲线就是值等于0的那条等值线。

程序绘制函数在f(x,y)=0和 f(x,y)-0.1 = 0时的曲线。

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 incs.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()

contour()levels參数指定所绘制等值线相应的函数值。这里设置levels參数为[0,0.1],因此终于将绘制两条等值线。

观察图会发现。表示隐函数f(x)=0蓝色实线并非全然连续的。在图的中间部分它由很多孤立的小段构成。

由于等值线在原点附近无限靠近,因此不管对函数f的取值空间怎样进行细分,总是会有无法分开的地方。终于造成了图中的那些孤立的细小区域。

而表示隐函数f(x,y)=0的红色虚线则是闭合且连续的。

contour()返回对象QuadContourSet

能够通过contour()返回对象获得等值线上每点的数据。以下我们在IPython中观察变量cs,它是一个 QuadContourSet 对象:

cs对象的collections属性是一个等值线列表,每条等值线用一个LineCollection对象表示:

>>> cs.collections

每一个LineCollection对象都有它自己的颜色、线型、线宽等属性,注意这些属性所获得的结果外面另一层封装,要获得其第0个元素才是真正的配置:

>>> c0.get_color()[0]

array([ 0., 0., 1., 1.])

>>> c0.get_linewidth()[0]

2

由类名可知,LineCollection对象是一组曲线的集合。因此它能够表示像蓝色实线那样由多条线构成的等值线。它的get_paths()方法获得构成等值线的全部路径,本例中蓝色实线

所表示的等值线由42条路径构成:

>>> len(cs.collections[0].get_paths())

42

路径是一个Path对象,通过它的vertices属性能够获得路径上全部点的坐标:

>>> path = cs.collections[0].get_paths()[0]

>>> type(path)

>>> path.vertices

array([[-0.08291457, -0.98938936],

[-0.09039269, -0.98743719],

…,

[-0.08291457, -0.98938936]])

上面的程序plt.subplot(122)就是从等值线集合cs中找到表示等值线的路径,并使用plot()将其绘制出来。

Matplotlib.pylab画图实例

{使用pylab模块}

matplotlib还提供了一个名为pylab的模块,当中包含了很多NumPy和pyplot模块中经常使用的函数,方便用户高速进行计算和画图,十分适合在IPython交互式环境中使用。这里使用以下的方式加载pylab模块:>>> import pylab as plNote:import pyplot as plt也相同能够两种经常使用图类型

Line and scatter plots(使用plot()命令), histogram(使用hist()命令)

1 折线图&散点图 Line and scatter plots

折线图 Line plots(关联一组x和y值的直线)import numpy as npimport pylab as plx = [1, 2, 3, 4, 5]# Make an array of x valuesy = [1, 4, 9, 16, 25]# Make an array of y values for each x valuepl.plot(x, y)# use pylab to plot x and ypl.show()# show the plot on the screen

plot(x, y) # plot x and y using default line style and colorplot(x, y, 'bo') # plot x and y using blue circle markersplot(y) # plot y using x as index array 0..N-1plot(y, 'r+') # ditto, but with red plusses

plt.plot(ks, wssses, marker='*', markerfacecolor='r', linestyle='-', color='b')

散点图 Scatter plots

把pl.plot(x, y)改成pl.plot(x, y, 'o')

美化 Making things look pretty

线条颜色 Changing the line color

红色:把pl.plot(x, y, 'o')改成pl.plot(x, y, ’or’)

线条样式 Changing the line style

虚线:plot(x,y, '--')

marker样式 Changing the marker style

蓝色星型markers:plot(x,y, ’b*’)

详细见附录- matplotlib中的作图參数

图和轴标题以及轴坐标限度 Plot and axis titles and limitsimport numpy as npimport pylab as plx = [1, 2, 3, 4, 5]# Make an array of x valuesy = [1, 4, 9, 16, 25]# Make an array of y values for each x valuepl.plot(x, y)# use pylab to plot x and ypl.title(’Plot of y vs. x’)# give plot a titlepl.xlabel(’x axis’)# make axis labelspl.ylabel(’y axis’)pl.xlim(0.0, 7.0)# set axis limitspl.ylim(0.0, 30.)pl.show()# show the plot on the screen

一个坐标系上绘制多个图 Plotting more than one plot on the same set of axes

依次作图就可以import numpy as npimport pylab as plx1 = [1, 2, 3, 4, 5]# Make x, y arrays for each graphy1 = [1, 4, 9, 16, 25]x2 = [1, 2, 4, 6, 8]y2 = [2, 4, 8, 12, 16]pl.plot(x1, y1, ’r’)# use pylab to plot x and ypl.plot(x2, y2, ’g’)pl.title(’Plot of y vs. x’)# give plot a titlepl.xlabel(’x axis’)# make axis labelspl.ylabel(’y axis’)pl.xlim(0.0, 9.0)# set axis limitspl.ylim(0.0, 30.)pl.show()# show the plot on the screen

图例 Figure legends

pl.legend((plot1, plot2), (’label1, label2’),loc='best’, numpoints=1)

第三个參数loc=表示图例放置的位置:'best’‘upper right’, ‘upper left’, ‘center’, ‘lower left’, ‘lower right’.

假设在当前figure里plot的时候已经指定了label,如plt.plot(x,z,label="cos(x2)"),直接调用plt.legend()就能够了。import numpy as npimport pylab as plx1 = [1, 2, 3, 4, 5]# Make x, y arrays for each graphy1 = [1, 4, 9, 16, 25]x2 = [1, 2, 4, 6, 8]y2 = [2, 4, 8, 12, 16]plot1 = pl.plot(x1, y1, ’r’)# use pylab to plot x and y : Give your plots namesplot2 = pl.plot(x2, y2, ’go’)pl.title(’Plot of y vs. x’)# give plot a titlepl.xlabel(’x axis’)# make axis labelspl.ylabel(’y axis’)pl.xlim(0.0, 9.0)# set axis limitspl.ylim(0.0, 30.)pl.legend([plot1, plot2], (’red line’, ’green circles’), ’best’, numpoints=1)# make legendpl.show()# show the plot on the screen

2 直方图 Histogramsimport numpy as npimport pylab as pl# make an array of random numbers with a gaussian distribution with# mean = 5.0# rms = 3.0# number of points = 1000data = np.random.normal(5.0, 3.0, 1000)# make a histogram of the data arraypl.hist(data)# make plot labelspl.xlabel(’data’)pl.show()

假设不想要黑色轮廓能够改为pl.hist(data, histtype=’stepfilled’)

自己定义直方图bin宽度 Setting the width of the histogram bins manually

添加两行

bins = np.arange(-5., 16., 1.) #浮点数版本号的range

pl.hist(data, bins, histtype=’stepfilled’)

同一画板上绘制多幅子图 Plotting more than one axis per canvas

假设须要同一时候绘制多幅图表的话,能够是给figure传递一个整数參数指定图标的序号。假设所指定

序号的画图对象已经存在的话。将不创建新的对象,而仅仅是让它成为当前画图对象。

fig1 = pl.figure(1)

pl.subplot(211)

subplot(211)把画图区域等分为2行*1列共两个区域, 然后在区域1(上区域)中创建一个轴对象. pl.subplot(212)在区域2(下区域)创建一个轴对象。

You can play around with plotting a variety of layouts. For example, Fig. 11 is created using the following commands:

f1 = pl.figure(1)

pl.subplot(221)

pl.subplot(222)

pl.subplot(212)

当画图对象中有多个轴的时候,能够通过工具栏中的Configure Subplotsbutton,交互式地调节轴之间的间距和轴与边框之间的距离。

假设希望在程序中调节的话,能够调用subplots_adjust函数。它有left, right, bottom, top, wspace, hspace等几个keyword參数,这些參数的值都是0到1之间的小数。它们是以画图区域的宽高为1进行正规化之后的坐标或者长度。

pl.subplots_adjust(left=0.08, right=0.95, wspace=0.25, hspace=0.45)

绘制圆形Circle和椭圆Ellipse

1. 调用包函数

###################################

# coding=utf-8

# !/usr/bin/env python

# __author__ = 'pipi'

# ctime 2014.10.11

# 绘制椭圆和圆形

###################################

from matplotlib.patches import Ellipse, Circle

import matplotlib.pyplot as plt

fig = plt.figure()

ax = fig.add_subplot(111)

ell1 = Ellipse(xy = (0.0, 0.0), width = 4, height = 8, angle = 30.0, facecolor= 'yellow', alpha=0.3)

cir1 = Circle(xy = (0.0, 0.0), radius=2, alpha=0.5)

ax.add_patch(ell1)

ax.add_patch(cir1)

x, y = 0, 0

ax.plot(x, y, 'ro')

plt.axis('scaled')

# ax.set_xlim(-4, 4)

# ax.set_ylim(-4, 4)

plt.axis('equal') #changes limits of x or y axis so that equal increments of x and y have the same length

plt.show()

參见Matplotlib.pdf Release 1.3.1文档

p187

18.7 Ellipses (see arc)

p631class matplotlib.patches.Ellipse(xy, width, height, angle=0.0, **kwargs)Bases: matplotlib.patches.PatchA scale-free ellipse.xy center of ellipsewidth total length (diameter) of horizontal axisheight total length (diameter) of vertical axisangle rotation in degrees (anti-clockwise)p626class matplotlib.patches.Circle(xy, radius=5, **kwargs)

或者參见Matplotlib.pdf Release 1.3.1文档contour绘制圆

#coding=utf-8

import numpy as np

import matplotlib.pyplot as plt

x = y = np.arange(-4, 4, 0.1)

x, y = np.meshgrid(x,y)

plt.contour(x, y, x**2 + y**2, [9]) #x**2 + y**2 = 9 的圆形

plt.axis('scaled')

plt.show()p478

Axes3D.contour(X, Y, Z, *args, **kwargs)

Create a 3D contour plot.

Argument Description

X, Y, Data values as numpy.arrays

Z

extend3d

stride

zdir

offset

Whether to extend contour in 3D (default: False)

Stride (step size) for extending contour

The direction to use: x, y or z (default)

If specified plot a projection of the contour lines on this position in plane normal to zdir

The positional and other

p1025

matplotlib.pyplot.axis(*v, **kwargs)

Convenience method to get or set axis properties.

2. 直接绘制

#coding=utf-8

'''

Created on Jul 14, 2014

@author: pipi

'''

from math import pi

from numpy import cos, sin

from matplotlib import pyplot as plt

if __name__ == '__main__':

'''plot data margin'''

angles_circle = [i*pi/180 for i in range(0,360)] #i先转换成double

#angles_circle = [i/np.pi for i in np.arange(0,360)] # <=>

# angles_circle = [i/180*pi for i in np.arange(0,360)] X

x = cos(angles_circle)

y = sin(angles_circle)

plt.plot(x, y, 'r')

plt.axis('equal')

plt.axis('scaled')

plt.show()

画图小技巧

控制坐标轴的显示——使x轴显示名称字符串而不是数字的两种方法

plt.xticks(range(len(list)), x, rotation='vertical')

Note:x代表一个字符串列表,如x轴上要显示的名称。

axes.set_xticklabels(x, rotation='horizontal', lod=True)

Note:这里axes是plot的一个subplot()

获取x轴上坐标最小最大值

xmin, xmax = plt.gca().get_xlim()

在指定坐标写文字

plt.text(max_x, 0, str(round(max_x, 2)))

绘制精美的图表

使用 python Matplotlib 库画图

barChart:http://www.cnblogs.com/qianlifeng/archive/2012/02/13/2350086.html魔法(Magic)命令%magic -%matplotlibinline

Gnuplot的介绍基于 Python Matplotlib 模块的高质量图形输出(2005年的文章有点旧)

matplotlib技巧集(绘制不连续函数的不连续点;參数曲线上绘制方向箭头;改动缺省刻度数目。Y轴不同区间使用不同颜色填充的曲线区域。

)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值