您的位置:首页 > 编程语言 > Python开发

Python学习(十一)——matplotlib与可视化

2017-08-12 20:13 716 查看
导入matplotlib模块:

import matplotlib as mpl


1、绘制线

给出x的序列及y与x的关系;

import matplotlib.pyplot as plt
x = np.arange(-5, 5, 0.2)
y = x**2
plt.plot(x,y,'r-',linewidth=2)
plt.show()


输出:



plt.plot(x,y,’r-‘,linewidth=2)中:r表示red红色(另:g-green、b-blue、m-magenta等),-表示实线

(另:其他不同的符号表示对应点

‘– ’ 虚线

‘+’ 加号+

‘x’ 乘号x

‘’ 星形

‘o’ 小圆

‘,’ 像素

‘. ’ 点

‘v’ 倒三角

‘^’ 正三角

‘<’ 朝左的三角

‘>’ 朝右的三角

‘_’ 水平短线

‘|’ 竖直短线

‘s’ 正方形

‘d’ 瘦菱形(30°)

‘D’ 菱形(90°)

‘p’ 正五边形

‘h’ 六边形1

‘H’ 六边形2

‘8’ 正八边形

等等,linewidth表示线宽;

可以用plt.xlabel、plt.ylabel为x、y轴添加label;

import matplotlib.pyplot as plt
x = np.arange(-5, 5, 0.2)
y = x**2
plt.plot(x,y,'r*',linewidth=2)
plt.ylabel('Number')
plt.xlabel('X')
plt.show()


输出:



胸型线:

x=np.arange(1,0,-0.001)
y=(-3*x*np.log(x)+np.exp(-(40*(x-1/np.e))**4)/25)/2
plt.figure(figsize=(5,7))
plt.plot(y,x,'r-',linewidth=2)
plt.grid(True)
plt.show()


输出:



心形线:

t=np.linspace(0,2*np.pi,100)
x=16*np.sin(t)**3
y=13*np.cos(t)-5*np.cos(2*t)-2*np<
105f0
/span>.cos(3*t)-np.cos(4*t)
plt.plot(x,y,'m-',linewidth=2)
plt.grid(True)
plt.show()


输出:



三叶玫瑰线:

theta = np.arange(0, 2*np.pi, 0.02)
x = np.sin(3*theta)*np.cos(theta)
y = np.sin(3*theta)*np.sin(theta)
plt.plot(x,y,'r-')
plt.ylabel('Y')
plt.xlabel('X')
plt.show()


输出:



四叶时为:

import matplotlib.pyplot as plt
import numpy as np
theta = np.arange(0, 2*np.pi, 0.02)
x = np.sin(2*theta)*np.cos(theta)
y = np.sin(2*theta)*np.sin(theta)
plt.plot(x,y,'r-')
plt.ylabel('Y')
plt.xlabel('X')
plt.show()


结果:



渐开线:

t=np.linspace(0,50,num=1000)
x=t*np.sin(t)+np.cos(t)
y=np.sin(t)-t*np.cos(t)
plt.plot(x,y,'r-',linewidth=2)
plt.grid()
plt.show()


输 出:



#!/usr/bin/python
# coding:utf-8

import numpy
import matplotlib.pyplot as plt

z = numpy.arange(-5, 5, .02)
# 定义一个矢量化函数
step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)
step = step_fn(z)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(z, step)
ax.set_ylim([-0.5, 1.5])
ax.set_xlim([-5,5])
# 绘制网格
ax.grid(True)
ax.set_xlabel('z')
ax.set_title('step function')

plt.show()


输出:



2、直方图

绘制全球人口数量前十名的国家:

import matplotlib.pyplot as plt
import numpy as np
labels= ["China","India","USA","Indonesia","Brasil","Pakistan","Nigeria","Bangladesh","Russian","Japan"]
quants= [1405372834,1304200000,322760000,257740000,205290000,192400000,182310000,164620000,146350000,126820000]
ind = np.linspace(0,9,10)
fig = plt.figure(1, figsize=(12,6))
ax= fig.add_subplot(111)
ax.bar(ind,quants,0.5,color='green')
ax.set_xticks(ind)
ax.set_xticklabels(labels)
ax.set_xlabel('Country')
ax.set_ylabel('Population')
# ax.set_title('Top 10 countries of the population', bbox={'facecolor':'0.5', 'pad':2})
ax.set_title('Top 10 countries of the population')
plt.show()


输出:



如:随机值

x=np.random.poisson(lam=5,size=10000)
pillar=15
a=plt.hist(x,bins=pillar,normed=True,range=[0,pillar],color='g')
plt.grid()
plt.show()


输出:



x=np.random.rand(10000)
t=np.arange(len(x))
plt.hist(x,30,color='b',alpha=0.5)
plt.legend(loc='upper left')
plt.grid()
plt.show()


输出:



x=np.random.rand(10000)
t=np.arange(len(x))
t=10000
a=np.zeros(1000)
for i in range(t):
a+=np.random.uniform(-5,5,1000)
a/=t
plt.hist(a,bins=30,color='g',alpha=0.5,normed=True)
plt.grid()
plt.show()


输出:



x=np.arange(0,10,0.1)
y=np.sin(x)
plt.bar(x,y,width=0.04,linewidth=0.2)
plt.plot(x,y,'r--',linewidth=2)
plt.title('Sin')
plt.xticks(rotation=-60)
plt.xlabel('x')
plt.ylabel('y')
plt.grid()
plt.show()


输出:



正态分布:

mu=2
sigma=3
data=mu+sigma*np.random.randn(1000)
h=plt.hist(data,30,normed=1,color='#00f0f0')
x=h[1]
y=norm.pdf(x,loc=mu,scale=sigma)
plt.plot(x,y,'r--',x,y,'bo',linewidth=2,markersize=4)
plt.grid()
plt.show()


输出:



3、饼状图

绘制全球人口数量前十名的国家;

import matplotlib.pyplot as plt
labels= ["China","India","USA","Indonesia","Brasil","Pakistan","Nigeria","Bangladesh","Russian","Japan"]
quants= [1405372834,1304200000,322760000,257740000,205290000,192400000,182310000,164620000,146350000,126820000]
plt.figure(1, figsize=(6,6))
colors  = ["red","blue","pink","coral","yellow","green","orange"]
plt.pie(quants, colors=colors, labels=labels, autopct='%1.1f%%',pctdistance=0.5, shadow=True)
# plt.title('Top 10 countries of the population')
plt.title('Top 10 countries of the population', bbox={'facecolor':'0.8','pad':5})
plt.show()


结果:



4、3D图:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot')
plt.show()


输出:



x,y=np.ogrid[-3:3:100j,-3:3:100j]
z=y*x*np.exp(-(x**2+y**2)/2)/math.sqrt(2*math.pi)
fig=plt.figure()
ax=fig.add_subplot(111,projection='3d')
ax.plot_surface(x, y, z, rstride=5, cstride=5, cmap=cm.Accent, linewidth=0.5)
plt.show()


输出:



from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

p = 3

u = np.linspace(0, 2*np.pi, 100)
v = np.linspace(0, np.pi, 100)

x = np.outer(np.power(np.cos(u), p), np.power(np.sin(v), p))
y = np.outer(np.power(np.sin(u), p), np.power(np.sin(v), p))
z = np.outer(np.ones(np.size(u)), np.power(np.cos(v), p))
# ax.plot_wireframe(x, y, z, rstride=5, cstride=5)
ax.plot_surface(x, y, z, rstride=2,cstride=1,alpha=0.8)
plt.xlim(-1,1)
plt.ylim(-1,1)
plt.show()


输出:



#!/usr/bin/env python
#coding:utf-8

import random
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

from mpl_toolkits.mplot3d import Axes3D

mpl.rcParams['font.size'] = 10

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

for z in [2015, 2016, 2017]:
xs = xrange(1,13)
ys = 1000 * np.random.rand(12)
#随机颜色
# color =plt.cm.Set2(random.choice(xrange(plt.cm.Set2.N)))
# 自定义颜色及透明度
color = ((1.0, 0.0, 0.0, 0.2),
(0.0, 1.0, 0.0, 0.2),
(0.0, 0.0, 1.0, 0.2))
ax.bar(xs, ys, zs=z, zdir='y', color=color, alpha=0.8)

ax.xaxis.set_major_locator(mpl.ticker.FixedLocator(xs))
ax.yaxis.set_major_locator(mpl.ticker.FixedLocator(ys))

ax.set_xlabel('Month')
ax.set_ylabel('Year')
ax.set_zlabel('Sales Net')

plt.show()


输出:



5.显示多副图片

from numpy.random import randn
import matplotlib.pyplot as plt

fig=plt.figure()

ax1=fig.add_subplot(2,2,1)
ax1.hist(randn(100),bins=20,color='r',alpha=0.3)
ax2=fig.add_subplot(2,2,2)
ax2.scatter(np.arange(30),np.arange(30)+3*randn(30))
ax3=fig.add_subplot(2,2,3)
plt.plot(randn(50).cumsum(),'g*')
ax4=fig.add_subplot(2,2,4)
plt.show()


打印结果为:



.

更多matplotlib示例

附:

1. matplotlib中的可选颜色:



2. matplotlib绘图可视化知识点整理

3. scatter设置颜色渐变条colorbar

4. Simple Exploration Notebook

5. Two Sigma RentHop EDA

6. Data Exploration Two Sigma Renthop
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: