from pylab import *
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
c, s = np.cos(x), np.sin(x)
plt.plot(x, c)
plt.plot(x, s)
show()
调用形式一般为:
plot([x], y, [fmt], data=None, **kwargs)
plot([x], y, [fmt], [x2], y2, [fmt2], …, **kwargs)
其中可选参数[fmt]是一个字符串,用于定义图的基本属性:颜色(color)、点型(marker)、线型(linestyle)
具体形式为:fmt = [color][marker][linestyle]
,注意这里的三个属性只能是每个属性的单个字母缩写,若属性用的是全名则不能用[fmt]参数来组合赋值
**kwargs参数:
from pylab import *
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
c, s = np.cos(x), np.sin(x)
plt.plot(x, c, 'b|-')
plt.plot(x, s)
show()
from pylab import *
import numpy as np
import matplotlib.pylab as plt
# 创建一个8*6点(point)的图,并设置分辨率为80
figure(figsize=(8, 6), dpi=80)
# 创建一个新的1*1的子图,接下来的图样绘制在其中的第一块中
subplot(1, 1, 1)
# 得到坐标点(x,y)坐标
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)
# 绘制余弦曲线,使用蓝色的、连续的、宽度为1的线条
plot(X, C, color='blue', linewidth=2.5, linestyle='-')
# 绘制正弦曲线,使用绿色的、连续的、宽度为1的线条
plot(X, S, color='green', linewidth=2.0, linestyle='-')
# 设置横轴的上下限
xlim(-4.0, 4.0)
# 设置横轴记号
xticks(np.linspace(-4, 4, 9, endpoint=True), fontproperties='Times New Roman', size=20)
# 设置纵轴记号
yticks(np.linspace(-1, 1, 5, endpoint=True))
#设置横纵坐标的名称以及对应字体格式
font = {'family' : 'Times New Roman',
'weight' : 'normal',
'size' : 20,
}
# 设置横轴标签
plt.xlabel('X axis', font)
# 设置纵轴标签
plt.ylabel('Y axis', font)
# 设置图像标题
plt.title('Demo Figure', font)
# 以分辨率72来保存图片
savefig('demo.png', dpi=72)
# 在屏幕上显示
show()
xlim(), ylim()
from pylab import *
import numpy as np
# 得到坐标点(x,y)坐标
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)
x_min, x_max = X.min(), X.max()
c_min, c_max = C.min(), C.max()
s_min, s_max = S.min(), C.max()
y_min, y_max = min(c_min, s_min), max(c_max, s_max)
# 设置横纵坐标上下界的偏移量,这样能够完整的显示图像且最美观
dx = (x_max - x_min) * 0.2
dy = (y_max - y_min) * 0.2
# 设置上下限
xlim(x_min - dx, x_max + dx)
ylim(y_min - dy, y_max + dy)
# 绘制余弦曲线,使用蓝色的、连续的、宽度为1的线条
plot(X, C, color='blue', linewidth=2.5, linestyle='-')
# 绘制正弦曲线,使用绿色的、连续的、宽度为1的线条
plot(X, S, color='green', linewidth=2.0, linestyle='-')
show()
xticks(), yticks()
这两个函数的用处在于指明横纵轴需要显示的内容和显示内容的位置,
参数的值可以有两种情况:
from pylab import *
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
c, s = np.cos(x), np.sin(x)
xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
yticks([-1, 0, +1],
[r'$-1$', r'$0$', r'$+1$'])
plt.plot(x, c)
plt.plot(x, s)
show()
坐标轴和上面的记号连在一起就形成了脊柱(Spines,一条线段上又一系列凸起,是不是很像脊柱),它记录了数据区域的范围,它们可以放在任意位置,不过默认是放在图的四边。
实际上每幅图都有四条脊柱(上下左右),为了将脊柱放在图的中间,我们必须将其中的两条(上和右)设置为无色,然后调整剩下的两条到合适的位置——数据空间的0点
from pylab import *
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
c, s = np.cos(x), np.sin(x)
plt.plot(x, c)
plt.plot(x, s)
# 设置坐标轴gca(),获取坐标轴信息
ax = gca()
'''
使用ax.spines[]选定边框,使用set_color()将选定的边框的颜色设为 none
'''
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
'''
移动坐标轴,将bottom即x坐标轴移动到y=0的位置
ax.xaixs为x轴,set_ticks_position()用于从上下左右(top/bottom/left/right)四条脊柱中选择一个作为x轴
使用set_position()设置边框位置:y=0的位置。位置的所有属性包括:outward、axes、data
'''
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
'''
将left 即y坐标轴设置到x=0的位置
'''
ax.yaxis.set_ticks_position('left') # 选定y轴
ax.spines['left'].set_position(('data', 0))
plt.show()
在plot()
函数中增加一个参数label
,再通过legend()
函数显示图例
from pylab import *
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
c, s = np.cos(x), np.sin(x)
plt.plot(x, c, label='cosine')
plt.plot(x, s, label='sine')
legend(loc='upper left')
show()
scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, hold=None, data=None, **kwargs)
函数用于在图像中绘制散点
参数:
annotate(s, xy, *args, **kwargs)
函数用于在图形上给数据点添加文本注解,而且支持带箭头的划线工具,方便我们在合适的位置添加描述信息。具体的内容可以参考Matplotlib中的annotate用法
参数:
arrowstyle
关键字来指定默认的可选类型,arrowstyle
关键字包含的默认类型包括以下:
如果没有arrowstyle
关键字,则箭头的样式可以由以下关键字指定(注意arrowstyle
和以下关键字不能同时存在)
箭头、坐标点和注释文本之间的关系属性包括如下图。其中connectionstyle属性用于控制注释点和注释文本之间的连接线的属性,比如弧度,角度之类的信息,这里还不是太清楚。
from pylab import *
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
c, s = np.cos(x), np.sin(x)
plt.plot(x, c)
plt.plot(x, s)
# 调整图像的脊柱
ax = gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left') # 选定y轴
ax.spines['left'].set_position(('data', 0))
# 在2*np.pi/3的位置给两条函数曲线加上一个注释
t = 2 * np.pi / 3
plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5,linestyle='--')
scatter([t, ], [np.cos(t), ], 50, color='blue')
annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
xy=(t, np.sin(t)), xycoords='data',
xytext=(+10, +30), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
plot([t,t],[0,np.sin(t)], color ='red', linewidth=2.5, linestyle="--")
scatter([t,],[np.sin(t),], 50, color ='red')
annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',color='green',
xy=(t, np.cos(t)), xycoords='data',
xytext=(-90, -50), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) # arc, angle, armA, rad
show()
图像的属性包括以下几个:
from pylab import *
'''
subplot()函数的参数中,除最后一维的其他维表示子图的大小,最后一维表示当前子图在图像中的位置,如下实例,在2*2的网格里,第四个子图为(2, 2, 4)
创建横跨多个位置的子图用gridspec实现
'''
"""
添加多个固定大小的子图:
fig = plt.figure(figsize=(10, 10), dpi=80, facecolor='red')
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 4)
ax1.plot() ...
ax2.plot() ...
"""
subplot(2,2,1)
xticks([]), yticks([])
text(0.5,0.5, 'subplot(2,2,1)',ha='center',va='center',size=20,alpha=.5)
subplot(2,2,2)
xticks([]), yticks([])
text(0.5,0.5, 'subplot(2,2,2)',ha='center',va='center',size=20,alpha=.5)
subplot(2,2,3)
xticks([]), yticks([])
text(0.5,0.5, 'subplot(2,2,3)',ha='center',va='center',size=20,alpha=.5)
subplot(2,2,4)
xticks([]), yticks([])
text(0.5,0.5, 'subplot(2,2,4)',ha='center',va='center',size=20,alpha=.5)
# savefig('../figures/subplot-grid.png', dpi=64)
show()
from pylab import *
import matplotlib.gridspec as gridspec
# gridspec的用法,可以使图像横跨多个坐标
G = gridspec.GridSpec(3, 3)
axes_1 = subplot(G[0, :])
xticks([]), yticks([])
text(0.5,0.5, 'Axes 1',ha='center',va='center',size=24,alpha=.5)
axes_2 = subplot(G[1,:-1])
xticks([]), yticks([])
text(0.5,0.5, 'Axes 2',ha='center',va='center',size=24,alpha=.5)
axes_3 = subplot(G[1:, -1])
# 确定了这个子图的位置之后,就可以直接在上面画图,直到创建了下个新的子图
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
c, s = np.cos(x), np.sin(x)
plt.plot(x, c)
plt.plot(x, s)
#xticks([]), yticks([])
#text(0.5,0.5, 'Axes 3',ha='center',va='center',size=24,alpha=.5)
axes_4 = subplot(G[-1,0])
xticks([]), yticks([])
'''
text()函数用于在图像上的特定位置加上一些文本,用于注释
'''
text(0.5,0.5, 'Axes 4',ha='center',va='center',size=24,alpha=.5)
axes_5 = subplot(G[-1,-2])
xticks([]), yticks([])
text(0.5,0.5, 'Axes 5',ha='center',va='center',size=24,alpha=.5)
#plt.savefig('../figures/gridspec.png', dpi=64)
show()
from pylab import *
'''
使用axes()函数来确定当前子图的位置和大小,参数为一个list[x, y, width, height],
x,y为当前子图的左下角坐标位置,width为子图的宽度,height为子图的高度
'''
axes([0.1,0.1,0.8,0.8])
xticks([]), yticks([])
text(0.6,0.6, 'axes([0.1,0.1,.8,.8])',ha='center',va='center',size=20,alpha=.5)
axes([0.2,0.2,.3,.3])
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
c, s = np.cos(x), np.sin(x)
plt.plot(x, c)
plt.plot(x, s)
# xticks([]), yticks([])
# text(0.5,0.5, 'axes([0.2,0.2,.3,.3])',ha='center',va='center',size=16,alpha=.5)
# plt.savefig("../figures/axes.png",dpi=64)
show()
from pylab import *
axes([0.1,0.1,.5,.5])
xticks([]), yticks([])
text(0.1,0.1, 'axes([0.1,0.1,.5,.5])',ha='left',va='center',size=16,alpha=.5)
axes([0.2,0.2,.5,.5])
xticks([]), yticks([])
text(0.1,0.1, 'axes([0.2,0.2,.5,.5])',ha='left',va='center',size=16,alpha=.5)
axes([0.3,0.3,.5,.5])
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
c, s = np.cos(x), np.sin(x)
plt.plot(x, c)
plt.plot(x, s)
# xticks([]), yticks([])
# text(0.1,0.1, 'axes([0.3,0.3,.5,.5])',ha='left',va='center',size=16,alpha=.5)
axes([0.4,0.4,.5,.5])
xticks([]), yticks([])
text(0.1,0.1, 'axes([0.4,0.4,.5,.5])',ha='left',va='center',size=16,alpha=.5)
# plt.savefig("../figures/axes-2.png",dpi=64)
show()
plt.fill_between(x, y1, y2, where, color, alpha)
参数:
一些实例可以参考基于matplotlib的数据可视化(图形填充函数fill和fill_between)
import numpy as np
import matplotlib.pyplot as plt
n = 256
X = np.linspace(-np.pi,np.pi,n,endpoint=True)
Y = np.sin(2*X)
plt.axes([0.025,0.025,0.95,0.95])
plt.plot (X, Y+1, color='blue', alpha=1.00)
plt.fill_between(X, 1, Y+1, color='blue', alpha=.25)
plt.plot (X, Y-1, color='blue', alpha=1.00)
plt.fill_between(X, -1, Y-1, (Y-1) > -1, color='blue', alpha=.25)
plt.fill_between(X, -1, Y-1, (Y-1) < -1, color='red', alpha=.25)
plt.xlim(-np.pi,np.pi), plt.xticks([])
plt.ylim(-2.5,2.5), plt.yticks([])
# savefig('../figures/plot_ex.png',dpi=48)
plt.show()
scatter()
前面已经详细讲过,这里不再赘述。
import numpy as np
import matplotlib.pyplot as plt
n = 1024
X = np.random.normal(0,1,n)
Y = np.random.normal(0,1,n)
T = np.arctan2(Y,X) # T中包含了数据点的颜色到当前colormap的映射值
# print(T.shape)
plt.axes([0.025,0.025,0.95,0.95])
plt.scatter(X,Y, s=75, c=T, alpha=.5)
plt.xlim(-1.5,1.5), plt.xticks([])
plt.ylim(-1.5,1.5), plt.yticks([])
# savefig('../figures/scatter_ex.png',dpi=48)
plt.show()
直方图和条形图外观上看上去差不多,但概念和实现上完全不同,需要加以区分:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
# 设置matplotlib正常显示中文和负号
matplotlib.rcParams['font.sans-serif']=['SimHei'] # 用黑体显示中文
matplotlib.rcParams['axes.unicode_minus']=False # 正常显示负号
# 随机生成(10000,)服从正态分布的数据
data = np.random.randn(10000)
"""
绘制直方图
data:必选参数,绘图数据
bins:直方图的长条形数目,可选项,默认为10
normed:是否将得到的直方图向量归一化,可选项,默认为0,代表不归一化,显示频数。normed=1,表示归一化,显示频率。
facecolor:长条形的颜色
edgecolor:长条形边框的颜色
alpha:透明度
"""
plt.hist(data, bins=40, normed=0, facecolor="blue", edgecolor="black", alpha=0.7)
# 显示横轴标签
plt.xlabel("区间")
# 显示纵轴标签
plt.ylabel("频数/频率")
# 显示图标题
plt.title("频数/频率分布直方图")
plt.show()
bar()
参数:
from pylab import *
n = 12
X = np.arange(n)
Y1 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n)
Y2 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n)
bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
bar(X, -Y2, facecolor='#ff9999', edgecolor='white')
#xticks(X)
for x,y in zip(X,Y1):
text(x, y+0.05, '%.2f' % y, ha='center', va= 'bottom')
for x, y in zip(X, -Y2):
text(x, y-0.15, '%.2f'% y, ha='center', va='bottom')
ylim(-1.25,+1.25)
show()
import matplotlib.pyplot as plt
import matplotlib
"""
多个数据样本进行对比时,要注意每个数据样本对应的颜色,对每个条形的注释文本设置和横纵坐标的设置
"""
# 设置中文字体和负号正常显示
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False
label_list = ['2014', '2015', '2016', '2017'] # 横坐标刻度显示值
num_list1 = [20, 30, 15, 35] # 纵坐标值1
num_list2 = [15, 30, 40, 20] # 纵坐标值2
x = range(len(num_list1))
# 绘制条形图
rects1 = plt.bar(x, height=num_list1, width=0.4, alpha=0.5, color='red', label='部门一')
rects2 = plt.bar([i+0.4 for i in x], height=num_list2, width=0.4, color='green', label='部门二')
# 设置y轴属性
plt.ylim(0, 50)
plt.ylabel('数量')
# 设置x轴属性
plt.xticks([index+0.2 for index in x], label_list)
plt.xlabel("年份")
plt.title('某某公司')
plt.legend()
# 显示文本
for rect in rects1:
height = rect.get_height()
plt.text(rect.get_x() + rect.get_width() / 2, height + 1, str(height), ha='center', va='bottom')
for rect in rects2:
height = rect.get_height()
plt.text(rect.get_x() + rect.get_width() / 2, height + 1, str(height), ha='center', va='bottom')
plt.show()
bar(y, width, height, left, *, align='center', **kwargs)
参数:
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False
price = [39.5, 39.9, 45.4, 38.9, 33.34]
# 绘制水平条形图
plt.barh(range(5), price, height=0.7, color='steelblue', alpha=0.5)
plt.yticks(range(5), ['亚马逊', '当当网', '中国图书网', '京东', '天猫'])
plt.xlim(30, 47)
plt.xlabel('价格')
plt.title('不同平台图书价格')
for x, y in enumerate(price):
plt.text(y+0.2, x-0.1, '%s'%y)
plt.show()
import matplotlib.pyplot as plt
import matplotlib
# 设置中文字体和负号正常显示
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False
label_list = ['2014', '2015', '2016', '2017']
num_list1 = [20, 30, 15, 35]
num_list2 = [15, 33, 40, 20]
y = range(1, len(num_list1)+1)
y = [index*1.5 for index in y]
plt.barh(y, num_list1, height=0.4, color='steelblue', alpha=0.5)
plt.barh([index-0.4 for index in y], num_list2, height=0.4, color='red', alpha=0.5)
plt.yticks([index-0.2 for index in y], label_list)
plt.ylabel('年份')
plt.xlim(0, 45)
plt.xlabel('数量')
for x, y1 in zip(num_list1, y):
plt.text(x+0.8, y1-0.1, str(x), ha='center', va='bottom')
for x, y2 in zip(num_list2, y):
plt.text(x+0.8, y2-0.5, str(x), ha='center', va='bottom')
plt.show()
import matplotlib.pyplot as plt
x = [52, 69, 58, 12, 39, 75]
y = [56, 15, 84, 65, 45, 48]
index = np.arange(len(x))
width = 0.3
plt.bar(index, height=x, width=width, color='blue', label=u'x', alpha=0.5)
plt.bar(index, height=y, width=width, color='gold', label=u'y') # 第二个图不能设置alpha值,不然透明的两个条形会出现重叠
plt.xlabel('index')
plt.ylabel('x/y')
plt.title('barplot stack', fontsize=20, color='gray')
plt.legend(loc='best')
plt.show()
X, Y = np.meshgrid(X, Y)
假设X为m维向量,Y为n维向量:
这样做可以使得X和Y中的每两个值互相都可以组成一个坐标点( x i , y j ),在将这些坐标点作为输入,通过一个 映射函数f ( x ) f(x)f(x)求值,就可以得到一个三维图形。
plt.contour()
这个函数用于绘制等高线图
import matplotlib.pyplot as plt
def f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n = 256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)
X,Y = np.meshgrid(x,y)
#print(X,'----', Y)
plt.contourf(X, Y, f(X,Y), 8, alpha=.75, cmap='jet')
C = plt.contour(X, Y, f(X,Y), 8, colors='black')
show()
import matplotlib.pyplot as plt
import numpy as np
p1={"编程能力":60,"沟通技能":70,"专业知识":65,"团体协作":75,"工具掌握":80} #创建第一个人的数据
p2={"编程能力":70,"沟通技能":60,"专业知识":75,"团体协作":65,"工具掌握":70} #创建第二个人的数据
# 分别提取两个人的信息和对应的标签
data1=np.array([i for i in p1.values()]).astype(int) #提取第一个人的信息
data2=np.array([i for i in p2.values()]).astype(int) #提取第二个人的信息
label=np.array([j for j in p1.keys()]) #提取标签
angle = np.linspace(0, 2*np.pi, len(data1), endpoint=False) #data里有几个数据,就把整圆360°分成几份
# 闭合的目的是在绘图时能够生成闭合的环
angles = np.concatenate((angle, [angle[0]])) #增加第一个angle到所有angle里,以实现闭合
data1 = np.concatenate((data1, [data1[0]])) #增加第一个人的第一个data到第一个人所有的data里,以实现闭合
data2 = np.concatenate((data2, [data2[0]])) #增加第二个人的第一个data到第二个人所有的data里,以实现闭合
fig = plt.figure()
ax = fig.add_subplot(111, polar=True) # 设置坐标轴为极坐标
# 绘制两个数据样本的闭合环
ax.plot(angles, data1, 'bo-', linewidth=2, color='green', alpha=0.5)
ax.fill(angles, data1, facecolor='red', alpha=0.2)
ax.plot(angles, data2, 'bo-', linewidth=2, color='blue', alpha=0.5) #
ax.fill(angles, data2, facecolor='steelblue', alpha=0.5)
# 设置圆周每一维上显示的样本
ax.set_thetagrids(angles * 180/np.pi, label, fontproperties='SimHei', color='gray', fontsize=13)
# 设置在半径方向上要显示的文本和显示文本的角度
ax.set_rgrids(np.arange(0, 81, 20),angle=45)
ax.set_rlim(0, 100)
ax.set_title('matplotlib 雷达图', va='bottom', fontproperties='SimHei', color='gold', fontsize=15)
#help(ax.set_thetagrids)
import numpy as np
import matplotlib.pyplot as plt
def plot_radar(data):
criterion = [1, 1, 1, 1, 1, 1] # 基准雷达图
angles = np.linspace(0, 2 * np.pi, 5, endpoint=False)
angles = np.concatenate((angles, [angles[0]]))
#print(criterion)
#print(angles)
fig = plt.figure(facecolor='#87CEEB') # 创建画板并填充颜色
ax = fig.add_subplot(111, polar=True,) # 设置坐标为极坐标
# 绘制三个五边形
floor = 0
ceil = 2
labels = np.array(['x1', 'x2', 'x3', 'x4', 'x5'])
# 绘制五边形的循环
for i in np.arange(floor, ceil + 0.5 ,0.5):
ax.plot(angles, [i] * (6), '-', lw= 0.5, color='black')
for i in range(5):
ax.plot([angles[i], angles[i]], [floor, ceil], '-',lw=0.5, color='black')
# 绘制雷达图
ax.plot(angles, criterion, 'b-', lw=2, alpha=0.4)
ax.fill(angles, criterion, facecolor='b', alpha=0.3) #填充
ax.plot(angles, data, 'b-', lw=2, alpha=0.35)
ax.fill(angles, data, facecolor='b', alpha=0.25)
ax.set_thetagrids(angles * 180 / np.pi, labels)
ax.spines['polar'].set_visible(False)#不显示极坐标最外的圆形
ax.set_theta_zero_location('N')#设置极坐标的起点(即0度)在正上方向
ax.grid(False)# 不显示分隔线
ax.set_yticks([]) # 不显示坐标间隔
ax.set_title('xxxxxxxxxxxx', va='bottom', fontproperties='SimHei')
ax.set_facecolor('#87ceeb') # 填充绘图区域的颜色
# 保存文png图片
plt.subplots_adjust(left=0.09, right=1, wspace=0.25, hspace=0.25, bottom=0.13, top=0.91)
plt.savefig('a_1.png')
plt.show()
data = [0.8, 0.9, 1.2, 1.0, 1.5, 0.8]
plot_radar(data)
import matplotlib.pyplot as plt
import numpy as np
N=20
theta=np.linspace(0,2*np.pi,N,endpoint=False)#均分角度
radii=10*np.random.rand(N)#随机角度
width=np.pi/4*np.random.rand(N)#随机宽度
ax=plt.subplot(111,projection='polar')#极坐标图绘制
bars=ax.bar(theta,radii,width=width,bottom=0.0)#哪个角度画,长度,扇形角度,从距离圆心0的地方开始画
for r,bar in zip(radii,bars):
bar.set_facecolor(plt.cm.viridis(r/10.0))
bar.set_alpha(0.5) #添加颜色
plt.title('polar')
plt.show()
import matplotlib.pyplot as plt
x = [5, 10, 15, 20, 25, 30, 35, 40]
y = [17, 24, 29, 36, 38, 47, 59, 80]
plt.plot(x, y, 'rs-', markersize=10)
灰度图和热力图的区别其实在于colormap的不同,灰度图采用的灰度map,而热力图一般采用的是多个颜色组成的彩色的map。
import numpy as np
import matplotlib.pyplot as plt
def f(x,y):
return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n = 10
x = np.linspace(-3,3,3.5*n)
y = np.linspace(-3,3,3.0*n)
X,Y = np.meshgrid(x,y)
Z = f(X,Y)
plt.axes([0.025,0.025,0.95,0.95])
plt.imshow(Z, interpolation='bicubic', cmap='bone', origin='lower')
plt.colorbar(shrink=0.92)
plt.xticks([]), plt.yticks([])
# savefig('../figures/imshow_ex.png', dpi=48)
plt.show()
import matplotlib.pyplot as plt
import matplotlib.colors as col
import matplotlib.cm as cm
import numpy as np
points = np.arange(-5, 5, 0.01)
# print(points)
xs, ys = np.meshgrid(points, points)
z = np.sqrt(xs**2 + ys**2)
# print(z)
# 自定义colormap
start_color = 'red'
end_color = 'blue'
cmap_1 = col.LinearSegmentedColormap.from_list('cmap1', [start_color, end_color])
plt.imshow(z, cmap=cmap_1, alpha=0.3)
plt.show()
以下为自定义的colormap实例。
import matplotlib.pyplot as plt
points = np.arange(-5, 5, 1)
# print(points)
xs, ys = np.meshgrid(points, points)
z = np.sqrt(xs**2 + ys**2)
# 列表中包含的颜色数目并不固定,可以选多个
color = ['red', 'green', 'blue']
cmap_1 = col.LinearSegmentedColormap.from_list('cmap1', [start_color, end_color])
plt.imshow(z, cmap=cmap_1, alpha=1)
plt.colorbar(shrink=0.92)
plt.show()
箱线图是一种用作显示一组数据分散情况的统计图
箱线图有五个参数,分别为:
箱线图各参数和正态分布之间的对比如下图:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
# 0、导入数据集
df = pd.read_excel('boxplot_data.xlsx', 'Sheet1')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.boxplot(df['Age'])
plt.show()
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False
label_list = ["第一部分", "第二部分", "第三部分"] # 各部分标签
size = [55, 35, 10] # 各部分大小
color = ["steelblue", "green", "blue"] # 各部分颜色
explode = [0.05, 0, 0] # 各部分突出值
"""
绘制饼图
explode:设置各部分突出
label:设置各部分标签,
labeldistance:设置标签文本距圆心位置,1.1表示1.1倍半径
autopct:设置圆里面文本
shadow:设置是否有阴影
startangle:起始角度,默认从0开始逆时针转
pctdistance:设置圆内文本距圆心距离
返回值
l_text:圆内部文本,matplotlib.text.Text object
p_text:圆外部文本
"""
patches, l_text, p_text = plt.pie(size, explode=explode, colors=color, labels=label_list,
labeldistance=1.1, autopct="%1.1f%%", shadow=True, startangle=90, pctdistance=0.6)
plt.axis("equal") # 设置横轴和纵轴大小相等,这样饼才是圆的
plt.legend()
plt.show()
help()
函数像matplotlib
这样的包在python中是非常多的,里面涉及大量的函数接口及其参数定义,想同时都记住是不可能也没有必要的,网上讲解各种函数的参数含义和使用的博客之类的资源很多,但大部分都不全,所以最靠谱的全面学习这些函数接口的方法应该是通过使用官方提供的help()
函数,当然官方文档是英文的,会对英语有一定要求,大家可以结合者官方文档和网上的博客来学习。下面举一个简单的例子,来说明一下help()
函数的用法。
import matplotlib.pyplot as plt
help(plt.figure)
Help on function figure in module matplotlib.pyplot:
figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class 'matplotlib.figure.Figure'>, clear=False, **kwargs)
Create a new figure.
Parameters
----------
num : integer or string, optional, default: None
If not provided, a new figure will be created, and the figure number
will be incremented. The figure objects holds this number in a `number`
attribute.
If num is provided, and a figure with this id already exists, make
it active, and returns a reference to it. If this figure does not
exists, create it and returns it.
If num is a string, the window title will be set to this figure's
`num`.
figsize : (float, float), optional, default: None
width, height in inches. If not provided, defaults to
:rc:`figure.figsize` = ``[6.4, 4.8]``.
dpi : integer, optional, default: None
resolution of the figure. If not provided, defaults to
:rc:`figure.dpi` = ``100``.
facecolor : color spec
the background color. If not provided, defaults to
:rc:`figure.facecolor` = ``'w'``.
edgecolor : color spec
the border color. If not provided, defaults to
:rc:`figure.edgecolor` = ``'w'``.
frameon : bool, optional, default: True
If False, suppress drawing the figure frame.
FigureClass : subclass of `~matplotlib.figure.Figure`
Optionally use a custom `.Figure` instance.
clear : bool, optional, default: False
If True and the figure already exists, then it is cleared.
Returns
-------
figure : `~matplotlib.figure.Figure`
The `.Figure` instance returned will also be passed to
new_figure_manager in the backends, which allows to hook custom
`.Figure` classes into the pyplot interface. Additional kwargs will be
passed to the `.Figure` init function.
Notes
-----
If you are creating many figures, make sure you explicitly call
:func:`.pyplot.close` on the figures you are not using, because this will
enable pyplot to properly clean up the memory.
`~matplotlib.rcParams` defines the default values, which can be modified
in the matplotlibrc file.