文章目录
同样的,Matplotlib官方的参考文档: https://matplotlib.org/api/index.html
里面有很多的绘制好的图表,我们如果需要非常细节的图形,可以找一个类似的模板然后传入我们需要的数据就可以了
官方提供的模板链接如下:https://matplotlib.org/gallery/index.html
我下面做一个简单的使用记录
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
Matplotlib的基本操作
# 最基本的一个图
plt.plot([1,2,3,4,5],[1,4,9,16,25])
plt.xlabel('xlabel',fontsize = 16)
plt.ylabel('ylabel')
Text(0, 0.5, 'ylabel')
以下是 常见的线条类型 使用
字符 | 类型 | 字符 | 类型 |
---|---|---|---|
'-' |
实线 | '--' |
虚线 |
'-.' |
虚点线 | ':' |
点线 |
'.' |
点 | ',' |
像素点 |
'o' |
圆点 | 'v' |
下三角点 |
'^' |
上三角点 | '<' |
左三角点 |
'>' |
右三角点 | '1' |
下三叉点 |
'2' |
上三叉点 | '3' |
左三叉点 |
'4' |
右三叉点 | 's' |
正方点 |
'p' |
五角点 | '*' |
星形点 |
'h' |
六边形点1 | 'H' |
六边形点2 |
'+' |
加号点 | 'x' |
乘号点 |
'D' |
实心菱形点 | 'd' |
瘦菱形点 |
'_' |
横线点 |
颜色
表示颜色的字符参数有:
字符 | 颜色 |
---|---|
‘b’ |
蓝色,blue |
‘g’ |
绿色,green |
‘r’ |
红色,red |
‘c’ |
青色,cyan |
‘m’ |
品红,magenta |
‘y’ |
黄色,yellow |
‘k’ |
黑色,black |
‘w’ |
白色,white |
# 指定不同的参数来绘图:下面简单介绍几种,了解即可
# 'bs'可以设置线条的形状和颜色(也可以通过color与linestyle分开设置)
# fontsize可以设置坐标轴字体的大小
# marker可以设置标志点的形状
# markerfacecolor可以设置标志的颜色
# markersize可以设置标志的大小
# alpha可以设置透明度
x = np.linspace(-10,10)
y = np.sin(x)
plt.plot(x,y,color='b',linestyle='-',marker = '*',markerfacecolor='y',markersize = 5,alpha = 0.4)
plt.xlabel('xlabel',fontsize = 16)
plt.ylabel('ylabel',fontsize = 16)
Text(0, 0.5, 'ylabel')
# 211 表示一会要画的图是2行一列的 最后一个1表示的是子图当中的第1个图
plt.subplot(211)
plt.plot(x,y,color='r')
# 212 表示一会要画的图是2行一列的 最后一个1表示的是子图当中的第2个图
plt.subplot(212)
plt.plot(x,y,color='b')
[<matplotlib.lines.Line2D at 0x19251924b48>]
# 211 表示一会要画的图是1行2列的 最后一个1表示的是子图当中的第1个图
plt.subplot(121)
plt.plot(x,y,color='k')
# 212 表示一会要画的图是1行2列的 最后一个1表示的是子图当中的第2个图
plt.subplot(122)
plt.plot(x,y,color='y')
[<matplotlib.lines.Line2D at 0x19252dc1a08>]
# 可以创建多行多列,如果当前的子图没有执行绘图操作,则该位置的子图会空出来
plt.subplot(221)
plt.plot(x,y,color='r')
plt.subplot(224)
plt.plot(x,y,color='b')
[<matplotlib.lines.Line2D at 0x19252f37e88>]
# 关于参数的用法和选择,详细的可以查看官方文档
# 添加解释和标注
plt.plot(x,y,color='k',linestyle='-',linewidth = 3,marker = 'o',markerfacecolor='r',markersize = 5)
plt.xlabel('x:---')
plt.ylabel('y:---')
# 图题
plt.title('title:Clichong')
# 在指定的位置添加注释
plt.text(0,0,'pos(0,0)')
#显示网络
plt.grid(True)
# 添加箭头,需给定其实和终止位置以及箭头的各种属性
plt.annotate('pos(-5,0)',xy=(-4,0),xytext=(-2.8,0.3),arrowprops = dict(facecolor='blue',shrink=0.15,headlength= 20,headwidth = 3))
# 将坐标轴隐藏
fig = plt.gca()
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
import math
x = np.random.normal(loc = 0.0,scale=1.0,size=300)
width = 0.5
bins = np.arange(math.floor(x.min())-width,math.ceil(x.max())+width,width)
ax = plt.subplot(111)
# 去掉上方和右方的坐标轴线
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
# 隐藏坐标轴上的锯齿线
plt.tick_params(bottom='off',top='off',left = 'off',right='off')
# 加入网络
plt.grid()
# 绘制直方图
plt.hist(x,alpha = 0.5,bins = bins)
(array([ 0., 3., 5., 14., 26., 53., 50., 54., 41., 31., 15., 7., 1.]),
array([-3.5, -3. , -2.5, -2. , -1.5, -1. , -0.5, 0. , 0.5, 1. , 1.5,
2. , 2.5, 3. ]),
<a list of 13 Patch objects>)
# legend函数实现给出颜色与类别的对应图,loc='best'是自动找到一个合适的位置,通过help(plt.legand)可以找到其他的参数
fig = plt.figure()
ax = plt.subplot(111)
x = np.arange(10)
for i in range(1,4):
plt.plot(x,i*x**2,label = 'Group %d'%i)
ax.legend(loc='upper center',bbox_to_anchor = (0.5,1.15) ,ncol=3)
<matplotlib.legend.Legend at 0x1925832da48>
风格设置
# 以下为可以调用的风格
plt.style.available
['bmh',
'classic',
'dark_background',
'fast',
'fivethirtyeight',
'ggplot',
'grayscale',
'seaborn-bright',
'seaborn-colorblind',
'seaborn-dark-palette',
'seaborn-dark',
'seaborn-darkgrid',
'seaborn-deep',
'seaborn-muted',
'seaborn-notebook',
'seaborn-paper',
'seaborn-pastel',
'seaborn-poster',
'seaborn-talk',
'seaborn-ticks',
'seaborn-white',
'seaborn-whitegrid',
'seaborn',
'Solarize_Light2',
'tableau-colorblind10',
'_classic_test']
# 尝试风格dark_background
x = np.linspace(-10,10)
y = np.sin(x)
plt.style.use('dark_background')
plt.plot(x,y)
[<matplotlib.lines.Line2D at 0x19258ad46c8>]
x = np.linspace(-10,10)
y = np.sin(x)
plt.xkcd()
plt.plot(x,y)
fig = plt.gca()
条形图
# 取消上诉的扭曲风格
# plt.xkcd(False)
np.random.seed(0)
x = np.arange(5)
y = np.random.randint(-5,5,5)
fig,axes = plt.subplots(ncols = 2)
# bar绘制正常的条形图
v_bars = axes[0].bar(x,y,color='red')
# barh绘制横着的条形图
h_bars = axes[1].barh(x,y,color='red')
# 通过子图索引设置各自的细节
axes[0].axhline(0,color='grey',linewidth=2)
axes[1].axvline(0,color='grey',linewidth=2)
plt.show()
# 数值
mean_values = [1,2,3]
# 误差棒
variance = [0.2,0.4,0.5]
# 名字
bar_label = ['bar1','bar2','bar3']
# 指定位置
x_pos = list(range(len(bar_label))) # [0, 1, 2, 3]
# 带有误差棒的条形图
plt.bar(x_pos,mean_values,yerr=variance,alpha=0.3)
# 可以自己设置坐标轴的取值范围
max_y = max(zip(mean_values,variance)) #(3, 0.5)
plt.ylim([0,(max_y[0]+max_y[1])*1.2])
# y轴标签
plt.ylabel('variable y')
# x轴标签
plt.xticks(x_pos,bar_label)
plt.show()
# 图像对应着绘图的结果
patterns = ('-', '+', 'x', '\\', '*', 'o', 'O', '.')
mean_value = range(1,len(patterns)+1)
# 确定每一个线条的位置
x_pos = list(range(len(mean_value)))
# 竖着画
bars = plt.bar(x_pos,mean_value,color='white')
# 通过参数设置条的样式
for bar,pattern in zip(bars,patterns):
bar.set_hatch(pattern)
plt.show()
data = range(200, 225, 5)
bar_labels = ['a', 'b', 'c', 'd', 'e']
y_pos = np.arange(len(data)) # array([0, 1, 2, 3, 4])
fig = plt.figure(figsize=(10,8))
# 设置y轴标签,用bar_labels带替y_pos
plt.yticks(y_pos, bar_labels, fontsize=16)
# 横着画
bars = plt.barh(y_pos,data,alpha = 0.5,color='g')
# 设置一条最低点的竖线
plt.vlines(min(data),-1,len(data)+0.5,linestyle = 'dashed')
# 设置每个条形图的数值
for b,d in zip(bars,data):
plt.text(b.get_width()+b.get_width()*0.05,b.get_y()+b.get_height()/2,'{0:.2%}'.format(d/min(data)))
plt.show()
盒图
盒图boxplot由最小值(min),下四分位数(q1),中位数(median),上四分位数(q3),最大值(max)五部分组成。
# 参数的介绍,详细的可查看参考文档,需要时再查阅
#print(help(plt.boxplot))
# 以下是一个简单的例子
tang_data = [np.random.normal(0,std,100) for std in range(1,4)]
fig = plt.figure(figsize = (8,6))
plt.boxplot(tang_data,notch=False,sym='s',vert=True)
plt.xticks([y+1 for y in range(len(tang_data))],['x1','x2','x3'])
plt.xlabel('x')
plt.title('box plot')
Text(0.5, 1.0, 'box plot')
直方图
data = np.random.normal(0,20,1000)
bins = np.arange(-100,100,5)
plt.hist(data,bins=bins)
# 由于会堆叠在一起,可以调整x坐标轴
#plt.xlim([min(data)-5,max(data)+5])
plt.show()
import random
# 两个类别来对比
data1 = [random.gauss(15,10) for i in range(500)]
data2 = [random.gauss(5,5) for i in range(500)]
# 指定区间
bins = np.arange(-50,50,2.5)
# 别分绘制,为了避免重叠需要设置透明度aplha
plt.hist(data1,bins=bins,label='class 1',alpha = 0.3)
plt.hist(data2,bins=bins,label='class 2',alpha = 0.3)
# 自动分配颜色既放置在合适位置
plt.legend(loc='best')
plt.show()
散点图
N = 1000
x = np.random.randn(N)
y = np.random.randn(N)
# 绘制散点图
plt.scatter(x,y,alpha=0.5)
#plt.legend(loc='best')
# plt.grid(True)
plt.show()
3D图
# 需要额外的导入绘制3D图的工具
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111,projection = '3d')
#ax = fig.gca(projection='3d')
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
xs = np.arange(20)
ys = np.random.rand(20)
cs = [c]*len(xs)
ax.bar(xs,ys,zs = z,zdir='y',color = cs,alpha = 0.5)
plt.show()
fig = plt.figure()
ax = fig.add_subplot(111,projection = '3d')
#( 设置-4π~4π的取值范围,数量为100个)
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
#( 设置-2~2的取值范围,数量为100个)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x,y,z)
#plt.show()
[<mpl_toolkits.mplot3d.art3d.Line3D at 0x1b03fbd5608>]
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
xs = np.arange(20) # 0-20的数组
ys = np.random.rand(20) # 0-1取值范围的随机小数数组
cs = [c]*len(xs) # 颜色取值数组
ax.bar(xs,ys,zs = z,zdir='y',color = cs,alpha = 0.5)
plt.show()
圆饼图
m = 51212.
f = 40742.
m_perc = m/(m+f)
f_perc = f/(m+f)
colors = ['navy','lightcoral']
labels = ["Male","Female"]
plt.figure(figsize=(8,8))
paches,texts,autotexts = plt.pie([m_perc,f_perc],labels = labels,autopct = '%1.1f%%',explode=[0,0.05],colors = colors)
for text in texts+autotexts:
text.set_fontsize(20)
for text in autotexts:
text.set_color('white')
布局设置
# 3x3的布局,第一个子图
ax1 = plt.subplot2grid((3,3),(0,0))
# 布局大小都是3z3,各自的位置不同
ax2 = plt.subplot2grid((3,3),(1,0))
# 占用一些位置,一个顶3个
ax3 = plt.subplot2grid((3,3),(0,2),rowspan=3)
#同上,越界一个顶两个
ax4 = plt.subplot2grid((3,3),(2,0),colspan = 2)
ax5 = plt.subplot2grid((3,3),(0,1),rowspan=2)
x = np.linspace(0,10,1000)
y1 = x**2
y2 = np.sin(x**2)
fig,ax1 = plt.subplots()
# 设置嵌套图位置,其参数分别表示:
# left:绘图区左侧边缘线与Figure画布左侧边缘线的距离
# Bottom:绘图区底侧边缘线与Figure画布底侧边缘线的距离
# width:绘图区的宽度
# height:绘图区的高度
left,bottom,width,height = [0.22,0.45,0.3,0.35]
#加入嵌套图
ax2 = fig.add_axes([left,bottom,width,height])
# 分别绘制
ax1.plot(x,y1)
ax2.plot(x,y2)
[<matplotlib.lines.Line2D at 0x1b0419bba48>]
模板引用
示例1:Horizontal bar chart模板
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(100)
plt.rcdefaults()
fig, ax = plt.subplots()
# Example data
people = ('A', 'B', 'C', 'D', 'E')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))
ax.barh(y_pos, performance, xerr=error, align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis() # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')
plt.show()
示例2:Creating annotated heatmaps
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
vegetables = ["cucumber", "tomato", "lettuce", "asparagus",
"potato", "wheat", "barley"]
farmers = ["Farmer Joe", "Upland Bros.", "Smith Gardening",
"Agrifun", "Organiculture", "BioGoods Ltd.", "Cornylee Corp."]
harvest = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0],
[2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0],
[1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0],
[0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0],
[0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0],
[1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1],
[0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]])
fig, ax = plt.subplots()
im = ax.imshow(harvest)
# We want to show all ticks...
ax.set_xticks(np.arange(len(farmers)))
ax.set_yticks(np.arange(len(vegetables)))
# ... and label them with the respective list entries
ax.set_xticklabels(farmers)
ax.set_yticklabels(vegetables)
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
for i in range(len(vegetables)):
for j in range(len(farmers)):
text = ax.text(j, i, harvest[i, j],
ha="center", va="center", color="w")
ax.set_title("Harvest of local farmers (in tons/year)")
fig.tight_layout()
plt.show()