python可视化学习笔记--matplotlib初识

python可视化--matplotlib初识

示例1.构造x和y列表画图

x \in [-\pi , \pi] , x分为200等份

y=sin(x)

绘制x,y的曲线图

import math
import matplotlib.pyplot as plt
%matplotlib inline #%开头,jupyter里面的魔法函数
samples = 200

xRange = (-math.pi,math.pi) #元组
x,y=[],[]

for i in range(samples):
    step_x = (xRange[1]-xRange[0])/samples
    x.append(xRange[0]+(i*step_x))
    y.append(math.sin(x[-1]))

plt.plot(x,y)
plt.show()

进阶1-1:利用NumPy构造坐标

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

%matplotlib inline

samples = 200

xRange = (-math.pi,math.pi)
x,y=np.zeros(samples),np.zeros(samples)

for i in range(samples):
    step_x = (xRange[1]-xRange[0])/samples
    x[i] = xRange[0]+(i*step_x)
    y[i] = math.sin(x[i])

plt.plot(x,y)
plt.show()

进阶1-2:利用Numpy+ linspace构造坐标

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

%matplotlib inline

x = np.linspace(-math.pi,math.pi,num = 200)#num 内置名,不能自定义
y = np.sin(x)

plt.plot(x,y)
plt.show()

示例2:图片保存(eps,jpg,png)

plt.save.fig('sin-plot.png')#图像保存

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

%matplotlib inline

x = np.linspace(-math.pi,math.pi,num = 200)#num 内置名,不能自定义
y = np.sin(x)

plt.plot(x,y)
plt.save.fig('sin-plot.png')#图像保存

示例3:画多条曲线

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

%matplotlib inline

x = np.linspace(-math.pi,math.pi,num = 200)#num 内置名,不能自定义
y = np.sin(x)
z = np.cos(x)

plt.plot(x,y)
plt.plot(x,z)
plt.show()#多条画完再show

示例4:指定线条的类型

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

%matplotlib inline

x = np.linspace(-math.pi,math.pi,num = 200)#num 内置名,不能自定义
y = np.sin(x)
z = np.cos(x)

plt.plot(x,y,'g--',linewidth = 5)
plt.plot(x,z,'r')

plt.show()#多条画完再show

进阶4-1 其他线型设置

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

x = np.linspace(-math.pi, math.pi, num = 200)
y = np.sin(x)
z = np.cos(x)
 
# Markers can be ’ . ’ , ’ , ’ , ’ o ’ , ’ 1 ’ and more     
plt.plot(x, y, 'r--', marker = 'o', markersize = 4)
plt.plot(x, z,'g--', marker = '1',linewidth = 2)#marker = '1'是数字1,不是字母L的小写
plt.show()

示例5:为图配上题注 

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

x = np.linspace(-math.pi, math.pi, num = 200)
y = np.sin(x)
z = np.cos(x)

plt.plot(x, y, 'r--', label= 'sin(x)')
plt.plot(x, z,'b-',linewidth = 4, label = 'cos(x)')

plt.legend(loc = 'left')# legend location can be 'best' , ' center' , 'left' , 'right ' ,etc.
plt.show()

进阶5-1:高级一点的图注

下面的两个结果图,分别是包含ax.axis('equal')和注释掉ax.axis('equal')的结果

import numpy as np
import matplotlib.pyplot as plt

fig,ax = plt.subplots()#创建总画布/figure“窗口”
lines = []
styles = ['-','--','-.',':']
colors = ['red','blue','green','black']
x = np.linspace(0,10,100)
for i in range(len(styles)):
    lines += ax.plot(x,np.sin(x-i*np.pi/2),styles[i],color=colors[i])

ax.axis('equal')#避免比例压缩为椭圆,下面第二个结果图是注释掉此行代码的结果
ax.legend(lines[:2],['line1','line2'],loc='upper left',frameon = False)

from matplotlib.legend import Legend
leg = Legend(ax,lines[2:],['line3','line4'],loc = 'lower left',frameon = False)
ax.add_artist(leg)

示例6:设置x或y轴范围

下面的结果左图是设置y轴范围:axis.set_ylim(-0.5*math.pi,0.5*math.pi) 

右图是默认的结果

import math
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-math.pi,math.pi,num = 200)
y = np.sin(x)
z = np.cos(x)

fig = plt.figure()
axis = fig.add_subplot(111)

axis.set_ylim(-0.5*math.pi,0.5*math.pi) #设置y轴范围

plt.plot(x,y,'r--',label = 'sin(x)')
plt.plot(x,z,'g--',label = 'cos(x)')
plt.legend(loc = 'upper left')

plt.show()

示例7:子图参数的意义

ax = fig.add_subplot(246)

参数246的意思是:将画布分割成2行4列,图像画在从左到右从上到下的第6块,从1开始数

import math
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-math.pi,math.pi,num = 200)
y = np.sin(x)
z = np.cos(x)
v = np.tan(x)
w = 1/v

fig = plt.figure()
axis = fig.add_subplot(221)#画布分割成2行2列,从左到右,从上到下的第一个画面,即左上
plt.plot(x,y,'r--',label = 'sin(x)')
plt.legend(loc = 'upper left')

axis = fig.add_subplot(222)#右上
plt.plot(x,z,'g--',label = 'cos(x)')
plt.legend(loc = 'lower center')

axis = fig.add_subplot(223)#左下
plt.plot(x,v,'b--',label = 'tan(x)')
plt.legend(loc = 'lower right')

axis = fig.add_subplot(224)#右下
plt.plot(x,w,'y--',label = 'cot(x)')
plt.legend(loc = 'lower left')

plt.show()

示例8:散点图

plt.scatter(x,y)

np.random.seed(19680801)#保证每次产生的随机数一样,具有可重复性;注释掉之后每次产生的随机数不同

import matplotlib.pyplot as plt
import numpy as np
numPoints = 50
x = np.random.standard_normal(numPoints)
y = np.random.standard_normal(numPoints)

np.random.seed(19680801)#保证每次产生的随机数一样,具有可重复性;注释掉之后每次产生的随机数不同
colors = np.random.rand(numPoints)

areaSize = (20*x)**2 #散点的面积(大小)是对应点x坐标的20倍的平方
plt.scatter(x,y,s = areaSize,c = colors,alpha = 0.5)

plt.show()

示例9:利用Pandas 和seaborn

seaborn : 是对matplotlib的extend,是一个数据可视化库,提供更高级的API封装,在应用中更加的方便灵活。

seaborn的5种装饰风格

styles = ['darkgrid','dark','white','whitegrid','tricks'] # 颜色代表背景颜色,grid代表是否有网格

#加载python自带的鸢尾花数据集

from sklearn.datasets import load_iris

iris = load_iris()

其他参考:https://www.cnblogs.com/tecdat/p/9518521.html

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

sns.set(style = 'ticks')

iris = pd.read_csv('iris.csv',header = None)#数据文件可自定义
iris.columns = ['sepal_length','sepal_width','petal_length','petal_width','species']
sns.pairplot(iris,hue = 'species',diag_kind = 'kde',palette = 'muted')

plt.show

示例10:热力图

sns.heatmap

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

iris.columns = ['sepal_length','sepal_width','petal_length','petal_width','species']
iris_corr = iris.corr()
sns.heatmap(iris_corr,annot=True,square=True,fmt='.2f',annot_kws={'size':16,'weight':'bold','color':'red'})

plt.show()

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值