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

1、绘制曲线

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

#!/usr/bin/python
# coding:utf-8
import numpy as np
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 numpy as np
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()

输出:
这里写图片描述

胸型线:

import numpy as np
import matplotlib as mpl
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()

输出:
这里写图片描述

心形线:

import matplotlib.pyplot as plt
import numpy as np

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.cos(3*t)-np.cos(4*t)
plt.plot(x,y,'m-',linewidth=2)
plt.grid(True)
plt.show()

输出:
这里写图片描述

三叶玫瑰线:

import matplotlib.pyplot as plt
import numpy as np

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

结果:

这里写图片描述

渐开线:

import matplotlib.pyplot as plt
import numpy as np

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

输出:

这里写图片描述

如:随机值

import matplotlib.pyplot as plt
import numpy as np

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

输出:
这里写图片描述

import matplotlib.pyplot as plt
import numpy as np

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

输出:
这里写图片描述

import matplotlib.pyplot as plt
import numpy as np
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()

输出:
这里写图片描述

import matplotlib.pyplot as plt
import numpy as np
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()

输出:
这里写图片描述

正态分布:

import matplotlib.pyplot as plt
import numpy as np

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
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]
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()

输出:
这里写图片描述

import matplotlib.pyplot as plt
import numpy as np
import math
from matplotlib import cm

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.显示多副图片
#!/usr/bin/env python
#coding:utf-8

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

打印结果为:

这里写图片描述

6.显示中文字符

首先导入FontProperties模块,然后设置字体属性font(加载字体文件),最后设置对应的fontproperties属性。
字体文件可以用自带字体文件或中文字体下载网下载。

示例,堆积条形图:

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

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

font = FontProperties(fname=r"迷你简丫丫.ttf", size=14)
N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N)   
p1 = plt.bar(ind, menMeans, 0.35, yerr=menStd)
p2 = plt.bar(ind, womenMeans, 0.35, bottom=menMeans, yerr=womenStd)

plt.ylabel('得分', fontproperties=font)
plt.title('按组和性别得分', fontproperties=font)
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Man', 'Woman'))
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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值