0%

Matplotlib的基本用法

Matplotlib的基本用法

简单的折线图

plt.plot(x,y, fortmat_string)

作用是定义画图的样式

x,y表示横纵左表, format可以定义画图格式

1
2
3
4
5
6
7
8
#导入Matploylib库
from matplotlib import pyplot as plt
%matplotlib inline
#画布上画图
plt.plot([1,2,3,4], [1,2,3,4], 'b', linewidth=2)
plt.plot([1,2,3,4], [1,4,9,16], 'r', linewidth=2)
#在画布上显示
plt.show()

png

添加标题标签及图的样式

1
2
3
4
5
6
7
8
9
10
11
12
from matplotlib import pyplot as plt  
%matplotlib inline
x = [5,2,7]
y = [2,16,4]
plt.plot(x,y)
# 图片的标题
plt.title('Image Title')
# 坐标轴Y轴
plt.ylabel('Y axis')
# 坐标轴X轴
plt.xlabel('X axis')
plt.show()

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from matplotlib import pyplot as plt
from matplotlib import style
style.use('ggplot')
x = [5,8,10]
y = [12,16,6]
x2 = [6,9,11]
y2 = [6,15,7]
plt.plot(x,y,'g',label='line one', linewidth=5)
plt.plot(x2,y2,'r',label='line two',linewidth=5)
plt.title('Epic Info')
plt.ylabel('Y axis')
plt.xlabel('X axis')
#设置图例位置
plt.legend()
plt.grid(True,color='k')
plt.show()

png

直方图

pyplot.bar(left, height, alpha=1, width=0.8, color=, edgecolor=, label=, lw=3)

画一个柱状图

参数

  • left: x轴的位置序列,一般采用arange函数产生一个序列
  • height: y轴的数值序列,也就是柱状图的高度,即我们需要展示的数据
  • alpha: 透明度
  • width: 柱状图的宽度
  • color or facecolor: 柱状图的填充颜色
  • edgecolor: 图形边缘颜色
  • label: 每个图像代表的意思
  • linewidth or linewidths or lw:边缘or线的宽度
1
2
3
4
5
6
7
8
from matplotlib import pyplot as plt 
plt.bar([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20],label="BMW", color='b', width=.5)
plt.bar([.75,1.75,2.75,3.75,4.75],[80,20,20,50,60],label="Audi", color='r',width=.5)
plt.legend()
plt.xlabel('Days')
plt.ylabel('Distance (kms)')
plt.title('Information')
plt.show()

png

频率图

matplotlib.pyplot.hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype=u’bar’, align=u’mid’, orientation=u’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False)

统计每个区间出现的频率

参数

  • x:直方图统计的数据
  • bins: 指定统计的间隔,如bins=10时表示以10为一个区间
  • color: 柱状图的颜色
  • histtype: 可选{‘bar’, ‘barstacked’,’step’, ‘stepfilled’}之一
  • density: 显示频率
  • stacked: 是否显示堆叠柱状图
1
2
3
4
5
6
7
8
import matplotlib.pyplot as plt
population_age = [22,55,62,45,21,22,34,42,42,4,2,102,95,85,55,110,120,70,65,55,111,115,80,75,65,54,44,43,42,48]
bins = [0,10,20,30,40,50,60,70,80,90,100]
plt.hist(population_age, bins=10, histtype='bar', color='b', rwidth=0.8)
plt.xlabel('age groups')
plt.ylabel('Number of people')
plt.title('Histogram')
plt.show()

png

散点图

1
2
3
4
5
6
7
8
9
10
11
12
13
import matplotlib.pyplot as plt
x = [1,1.5,2,2.5,3,3.5,3.6]
y = [7.5,8,8.5,9,9.5,10,10.5]
x1=[8,8.5,9,9.5,10,10.5,11]
y1=[3,3.5,3.7,4,4.5,5,5.2]
# scatter表示画散点图
plt.scatter(x,y, label='high income low saving',color='r')
plt.scatter(x1,y1,label='low income high savings',color='b')
plt.xlabel('saving*100')
plt.ylabel('income*1000')
plt.title('Scatter Plot')
plt.legend()
plt.show()

png

堆叠图

matplotlib.pyplot.stackplot(x, args, labels=(), colors=None, baseline=’zero’, data=None, *kwargs)

画堆叠图,主要有三个参数

  • x:需要画堆叠图的数值
  • laebl: 堆叠图中折现的标签
  • colors: 设置折线图的颜色
1
2
3
4
5
6
7
8
9
10
11
sleeping =[7,8,6,11,7]
eating = [2,3,4,3,2]
working =[7,8,7,2,2]
playing = [8,5,7,8,13]
labels = ['Sleeping', 'Eating', 'Working', 'Playing']
plt.stackplot(days, sleeping,eating,working,playing,labels=labels,colors=['m','c','r','k'])
plt.xlabel('x')
plt.ylabel('y')
plt.title('Stack Plot')
plt.legend()
plt.show()

png

饼状图

1
2
3
4
5
6
slices = [7,3,2,13]
activities = ['sleeping','eating','working','playing']
cols = ['c','m','r','b']
plt.pie(slices, labels=activities, colors=cols, startangle=90, shadow= True, explode=(0,0.1,0,0), autopct='%1.1f%%')
plt.title('Pie Plot')
plt.show()

png

多个子图合并

plt.subplot(numRows, numCols, plotNum)

将一块画布分为多个区域,将不同图分别放入不同的子图

参数

  • numRows:指的行数
  • numCols:指的列数
  • plotNum:子图的位置

如上面所示的221,表示的是将图分为2 * 2个子图,然后使用第一个位置

子图的位置依次为

1
2
3
(1,1) (1,2)

(2,1) (2,2)

依次对应的位置为1,2,3,4

1
2
3
4
5
6
7
8
9
10
11
import numpy as np
import matplotlib.pyplot as plt
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.subplot(221)
plt.plot(t1, f(t1), 'bo', t2, f(t2))
plt.subplot(222)
plt.plot(t2, np.cos(2*np.pi*t2))
plt.show()

png

pandas与matplotlib结合

1
2
3
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.rand(nums)

随即产生nums个位于[0,1]的样本

np.random.randn(nums)

随即返回nums个标准正态分布的样本

1
plt.plot(np.random.rand(10))
1
[<matplotlib.lines.Line2D at 0x24f3122c2b0>]

png

设置坐标轴刻度

  • 图名
  • x轴标签
  • y轴标签
  • 图例
  • x轴边界
  • y轴边界
  • x轴刻度
  • y轴刻度
  • x轴刻度标签
  • y轴刻度标签
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
df = pd.DataFrame(np.random.rand(10,2),columns=['A','B'])

fig = df.plot(figsize=(8,4)) # figsize:创建图表窗口,设置窗口大小


plt.title('TITLETITLETITLE') # 图名
plt.xlabel('XXXXXX') # x轴标签
plt.ylabel('YYYYYY') # y轴标签

plt.legend(loc = 'upper right') # 显示图例,loc表示位置

plt.xlim([0,12]) # x轴边界
plt.ylim([0,1.5]) # y轴边界

plt.xticks(range(10)) # 设置x刻度
plt.yticks([0,0.2,0.4,0.6,0.8,1.0,1.2]) # 设置y刻度

fig.set_xticklabels("%.1f" %i for i in range(10)) # x轴刻度标签
fig.set_yticklabels("%.2f" %i for i in [0,0.2,0.4,0.6,0.8,1.0,1.2]) # y轴刻度标签

# 这里x轴范围是0-12,但刻度只是0-9,刻度标签使得其显示1位小数
1
2
3
4
5
6
7
[Text(0, 0, '0.00'),
Text(0, 0, '0.20'),
Text(0, 0, '0.40'),
Text(0, 0, '0.60'),
Text(0, 0, '0.80'),
Text(0, 0, '1.00'),
Text(0, 0, '1.20')]

png

修改图标样式

pd.Series()作用是产生一个有编号的序列

np.random.randn()产生正太分布的样本,当只有一个参数是,返回n个标准正太分布的结果,当有两个或多个参数时,参数表示对应的维度

np.random.rand() 用法和上面一个函数一样,但是返回的是

np.cumsum()表示将前一行或者前一列加到后面

参数

​ a:表示传入函数的数据
axi:{0,1},axi=0时表示行相加,axi=1时表示列相加

1
2
s = pd.Series(np.random.randn(100).cumsum())
s.plot(linestyle = '--', marker = '.',color="r",grid=False)

png

dataframe直接画图

DataFrame.plot(x=None, y=None, kind=’line’, ax=None, subplots=False,
sharex=None, sharey=False, layout=None,figsize=None,
use_index=True, title=None, grid=None, legend=True,
style=None, logx=False, logy=False, loglog=False,
xticks=None, yticks=None, xlim=None, ylim=None, rot=None,
xerr=None,secondary_y=False, sort_columns=False, **kwds)

Parameters:
x : label or position, default None#指数据框列的标签或位置参数

y : label or position, default None

kind : str
‘line’ : line plot (default)#折线图
‘bar’ : vertical bar plot#条形图
‘barh’ : horizontal bar plot#横向条形图
‘hist’ : histogram#柱状图
‘box’ : boxplot#箱线图
‘kde’ : Kernel Density Estimation plot#Kernel 的密度估计图,主要对柱状图添加Kernel 概率密度线
‘density’ : same as ‘kde’
‘area’ : area plot#不了解此图
‘pie’ : pie plot#饼图
‘scatter’ : scatter plot#散点图 需要传入columns方向的索引
‘hexbin’ : hexbin plot#不了解此图

ax : matplotlib axes object, default None#子图(axes, 也可以理解成坐标轴) 要在其上进行绘制的matplotlib subplot对象。如果没有设置,则使用当前matplotlib subplot其中,变量和函数通过改变figure和axes中的元素(例如:title,label,点和线等等)一起描述figure和axes,也就是在画布上绘图。

  • subplots : boolean, default False#判断图片中是否有子图

Make separate subplots for each column

  • sharex : boolean, default True if ax is None else False#如果有子图,子图共x轴刻度,标签

In case subplots=True, share x axis and set some x axis labels to invisible; defaults to True if ax is None otherwise False if an ax is passed in; Be aware, that passing in both an ax and sharex=True will alter all x axis labels for all axis in a figure!

  • sharey : boolean, default False#如果有子图,子图共y轴刻度,标签

In case subplots=True, share y axis and set some y axis labels to invisible

  • layout : tuple (optional)#子图的行列布局

(rows, columns) for the layout of subplots

  • figsize : a tuple (width, height) in inches#图片尺寸大小

  • use_index : boolean, default True#默认用索引做x轴

Use index as ticks for x axis

  • title : string#图片的标题用字符串

Title to use for the plot

  • grid : boolean, default None (matlab style default)#图片是否有网格

Axis grid lines

  • legend : False/True/’reverse’#子图的图例,添加一个subplot图例(默认为True)

Place legend on axis subplots

  • style : list or dict#对每列折线图设置线的类型

matplotlib line style per column

  • logx : boolean, default False#设置x轴刻度是否取对数

Use log scaling on x axis

  • logy : boolean, default False

Use log scaling on y axis

  • loglog : boolean, default False#同时设置x,y轴刻度是否取对数

Use log scaling on both x and y axes

  • xticks : sequence#设置x轴刻度值,序列形式(比如列表)

Values to use for the xticks

  • yticks : sequence#设置y轴刻度,序列形式(比如列表)

Values to use for the yticks

  • xlim : 2-tuple/list#设置坐标轴的范围,列表或元组形式

  • ylim : 2-tuple/list

  • rot : int, default None#设置轴标签(轴刻度)的显示旋转度数

Rotation for ticks (xticks for vertical, yticks for horizontal plots)

  • fontsize : int, default None#设置轴刻度的字体大小

Font size for xticks and yticks

  • colormap : str or matplotlib colormap object, default None#设置图的区域颜色

Colormap to select colors from. If string, load colormap with that name from matplotlib.

  • colorbar : boolean, optional #图片柱子

If True, plot colorbar (only relevant for ‘scatter’ and ‘hexbin’ plots)

  • position : float

Specify relative alignments for bar plot layout. From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center)

  • layout : tuple (optional) #布局

(rows, columns) for the layout of the plot

  • table : boolean, Series or DataFrame, default False #如果为正,则选择DataFrame类型的数据并且转换匹配matplotlib的布局。

If True, draw a table using the data in the DataFrame and the data will be transposed to meet matplotlib’s default layout. If a Series or DataFrame is passed, use passed data to draw a table.

  • yerr : DataFrame, Series, array-like, dict and str

See Plotting with Error Bars for detail.

  • xerr : same types as yerr.

  • stacked : boolean, default False in line and

bar plots, and True in area plot. If True, create stacked plot.

  • sort_columns : boolean, default False # 以字母表顺序绘制各列,默认使用前列顺序

  • secondary_y : boolean or sequence, default False ##设置第二个y轴(右y轴)

Whether to plot on the secondary y-axis If a list/tuple, which columns to plot on secondary y-axis

  • mark_right : boolean, default True

When using a secondary_y axis, automatically mark the column labels with “(right)” in the legend

  • kwds : keywords

Options to pass to matplotlib plotting method

Returns:axes : matplotlib.AxesSubplot or np.array of them

1
2
3
4
5
# 直接用风格样式设置
# 透明度与颜色版
# s.plot(style="--.",alpha = 0.8,colormap = 'Reds_r')
df = pd.DataFrame(np.random.randn(100, 4),columns=list('ABCD')).cumsum()
df.plot(style = '--.',alpha = 0.8,colormap = 'summer_r')
1
<matplotlib.axes._subplots.AxesSubplot at 0x24f379a4cc0>

png

1
2
3
df = pd.DataFrame(np.random.randn(10,2))
df.plot(style = '--o')
plt.text(5,0.5,'Hello',fontsize=12)
1
Text(5, 0.5, 'Hello')

png

子图绘制

figure对象

plt.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=, **kwargs)

作用创建一块画布

num相当于id,如果没有id则递增创建,如果已存在则返回该存在的对象

1
2
3
4
fig1 = plt.figure(num=1,figsize=(8,6))
plt.plot(np.random.rand(50).cumsum(),'k--')
fig2 = plt.figure(num=2,figsize=(8,6))
plt.plot(50-np.random.rand(50).cumsum(),'k--')
1
[<matplotlib.lines.Line2D at 0x24f3780f6d8>]

png

png

先创建子图然后填充

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 先建立子图然后填充图表
fig = plt.figure(figsize=(10,6),facecolor = 'gray')

# 第一个子图曲线图
ax1 = fig.add_subplot(2,2,1)
plt.plot(np.random.rand(50).cumsum(),'k--')
plt.plot(np.random.randn(50).cumsum(),'b--')
# 第二个字图,直方图
ax2 = fig.add_subplot(2,2,2)
ax2.hist(np.random.rand(50),alpha=0.4)

# 第三个饼状图
slices = [7,3,2,13]
activities = ['sleeping','eating','working','playing']
cols = ['c','m','r','b']
ax3 = fig.add_subplot(223)
ax3.pie(slices, labels=activities, colors=cols, startangle=90, shadow= True, explode=(0,0.1,0,0), autopct='%1.1f%%')

# 第四个折线图
ax4 = fig.add_subplot(2,2,4)
df2 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
ax4.plot(df2,alpha=0.5,linestyle='--',marker='.')
1
2
3
4
[<matplotlib.lines.Line2D at 0x24f38c19940>,
<matplotlib.lines.Line2D at 0x24f3905ed68>,
<matplotlib.lines.Line2D at 0x24f3905ef28>,
<matplotlib.lines.Line2D at 0x24f3906b0f0>]

png

使用subplots子图数组填充子图

1
2
3
4
5
6
7
8
9
10
# 创建一个新的figure,并返回一个subplot对象的numpy数组 → plt.subplot

fig,axes = plt.subplots(2,3,figsize=(10,4))
ts = pd.Series(np.random.randn(1000).cumsum())
print(axes, axes.shape, type(axes))
# 生成图表对象的数组

# 通过数组访问对应的子图
ax1 = axes[0,1]
ax1.plot(ts)
1
2
3
4
5
6
[[<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F38EFABA8>
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F38F13BA8>
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F38CA4C88>]
[<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F38CC8DA0>
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F38CECEB8>
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F38D17320>]] (2, 3) <class 'numpy.ndarray'>
1
[<matplotlib.lines.Line2D at 0x24f38d39978>]

png

1
2
3
4
5
6
7
8
9
10
# plt.subplots 参数调整
fig,axes = plt.subplots(2,2,sharex=True,sharey=True)
# sharex,sharey:是否共享x,y刻度

for i in range(2):
for j in range(2):
axes[i,j].hist(np.random.randn(500),color='k',alpha=0.5)

# wspace,hspace:用于控制宽度和高度的百分比,比如subplot之间的间距
plt.subplots_adjust(wspace=0,hspace=0)

png

多系列子图绘制

plt.plot():

  • subplots, 是否分别绘制子图,为true的时候表示分开绘制,为false表示在一个图立面绘制
  • layout:挥之子图矩阵,按顺序填充

subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

有六个可选参数来控制子图布局。值均为0~1之间。其中left、bottom、right、top围成的区域就是子图的区域。wspace、hspace分别表示子图之间左右、上下的间距。实际的默认值由matplotlibrc文件控制的。

1
2
3
4
5
6
7
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
df.plot(style = '--.',alpha = 0.4,grid = True,figsize = (20,8),
subplots = True,
layout = (2,2),
sharex = False)
plt.subplots_adjust(wspace=0.1,hspace=0.2)

png

基本图表绘制

Series 与 DataFrame 绘图

plt.plot(kind=’line’, ax=None, figsize=None, use_index=True, title=None, grid=None, legend=False,
style=None, logx=False, logy=False, loglog=False, xticks=None, yticks=None, xlim=None, ylim=None,
rot=None, fontsize=None, colormap=None, table=False, yerr=None, xerr=None, label=None, secondary_y=False, **kwds)

参数含义:

  • series的index为横坐标
  • value为纵坐标
  • kind → line,bar,barh…(折线图,柱状图,柱状图-横…)
  • label → 图例标签,Dataframe格式以列名为label
  • style → 风格字符串,这里包括了linestyle(-),marker(.),color(g)
  • color → 颜色,有color指定时候,以color颜色为准
  • alpha → 透明度,0-1
  • use_index → 将索引用为刻度标签,默认为True
  • rot → 旋转刻度标签,0-360
  • grid → 显示网格,一般直接用plt.grid
  • xlim,ylim → x,y轴界限
  • xticks,yticks → x,y轴刻度值
  • figsize → 图像大小
  • title → 图名
  • legend → 是否显示图例,一般直接用plt.legend()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) # pandas 时间序列
ts = ts.cumsum()
ts.plot(kind='line',
label = "what",
style = '--.',
color = 'g',
alpha = 0.4,
use_index = True,
rot = 45,
grid = True,
ylim = [-50,50],
yticks = list(range(-50,50,10)),
figsize = (8,4),
title = 'TEST_TEST',
legend = True)
# 对网格项进行更加细致的设置
#plt.grid(True, linestyle = "--",color = "gray", linewidth = "0.5",axis = 'x') # 网格
plt.legend()
plt.show()

png

1
2
3
4
5
6
7
8
9
10
11
12
13
# subplots → 是否将各个列绘制到不同图表,默认False
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD')).cumsum()
df.plot(kind='line',
style = '--.',
alpha = 0.4,
use_index = True,
rot = 45,
grid = True,
figsize = (8,4),
title = 'test',
legend = True,
subplots = False,
colormap = 'Greens')
1
<matplotlib.axes._subplots.AxesSubplot at 0x24f32b0f630>

png

柱状图

  • plt.bar()
    • x,y参数:x,y值
    • width:宽度比例
    • facecolor柱状图里填充的颜色、edgecolor是边框的颜色
    • left-每个柱x轴左边界,bottom-每个柱y轴下边界 → bottom扩展即可化为甘特图 Gantt Chart
    • align:决定整个bar图分布,默认left表示默认从左边界开始绘制,center会将图绘制在中间位置
      xerr/yerr :x/y方向error bar
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 创建一个新的figure,并返回一个subplot对象的numpy数组
fig,axes = plt.subplots(4,1,figsize = (10,10))

s = pd.Series(np.random.randint(0,10,16),index = list('abcdefghijklmnop'))
df = pd.DataFrame(np.random.rand(10,3), columns=['a','b','c'])

# 单系列柱状图方法一:plt.plot(kind='bar/barh')
s.plot(kind='bar',color = 'k',grid = True,alpha = 0.5,ax = axes[0]) # ax参数 → 选择第几个子图

# 多系列柱状图
df = pd.DataFrame(np.random.rand(10,3), columns=['a','b','c'])
df.plot(kind='bar',ax = axes[1],grid = True,colormap='Reds_r')

# 多系列堆叠图
# stacked → 堆叠
df.plot(kind='bar',ax = axes[2],grid = True,colormap='Blues_r',stacked=True)

# The bars are positioned at y with the given align. Their dimensions are given by width and height. The horizontal baseline is left (default 0).
# https://matplotlib.org/api/_as_gen/matplotlib.pyplot.barh.html?highlight=barh#matplotlib.pyplot.barh
df.plot.barh(ax = axes[3],grid = True,stacked=True,colormap = 'BuGn_r')
1
<matplotlib.axes._subplots.AxesSubplot at 0x24f32cf0550>

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
plt.figure(figsize=(10,4))

x = np.arange(10)
y1 = np.random.rand(10)
y2 = -np.random.rand(10)

plt.bar(x,y1,width = 1,facecolor = 'yellowgreen',edgecolor = 'white',yerr = y1*0.1)
plt.bar(x,y2,width = 1,facecolor = 'lightskyblue',edgecolor = 'white',yerr = y2*0.1)

for i,j in zip(x,y1):
plt.text(i-0.2,j-0.15,'%.2f' % j, color = 'white')
for i,j in zip(x,y2):
plt.text(i-0.2,j+0.05,'%.2f' % -j, color = 'white')
# 给图添加text
# zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

png

面积图

  • stacked:是否堆叠,默认情况下,区域图被堆叠
  • 为了产生堆积面积图,每列必须是正值或全部负值!
  • 当数据有NaN时候,自动填充0,图标签需要清洗掉缺失值
1
2
3
4
5
6
7
fig,axes = plt.subplots(2,1,figsize = (8,6))

df1 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df2 = pd.DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])

df1.plot.area(colormap = 'Greens_r',alpha = 0.5,ax = axes[0])
df2.plot.area(stacked=False,colormap = 'Set2',alpha = 0.5,ax = axes[1])
1
<matplotlib.axes._subplots.AxesSubplot at 0x24f3288f668>

png

填图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
fig,axes = plt.subplots(2,1,figsize = (8,6))

x = np.linspace(0, 1, 500)
y1 = np.sin(4 * np.pi * x) * np.exp(-5 * x)
y2 = -np.sin(4 * np.pi * x) * np.exp(-5 * x)

axes[0].fill(x, y1, 'r',alpha=0.5,label='y1')
axes[0].fill(x, y2, 'g',alpha=0.5,label='y2')
# 对函数与坐标轴之间的区域进行填充,使用fill函数
# 也可写成:plt.fill(x, y1, 'r',x, y2, 'g',alpha=0.5)

x = np.linspace(0, 5 * np.pi, 1000)
y1 = np.sin(x)
y2 = np.sin(2 * x)
axes[1].fill_between(x, y1, y2, color ='b',alpha=0.5,label='area')
# 填充两个函数之间的区域,使用fill_between函数

for i in range(2):
axes[i].legend()
axes[i].grid()
# 添加图例、格网

png

饼图

plt.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, hold=None, data=None)

  • 参数含义:
    • 第一个参数:数据
    • explode:指定每部分的偏移量
    • labels:标签
    • colors:颜色
    • autopct:饼图上的数据标签显示方式
    • pctdistance:每个饼切片的中心和通过autopct生成的文本开始之间的比例
    • labeldistance:被画饼标记的直径,默认值:1.1
    • shadow:阴影
    • startangle:开始角度
    • radius:半径
    • frame:图框
    • counterclock:指定指针方向,顺时针或者逆时针
1
2
3
4
5
6
7
8
9
10
11
12
13
14
s = pd.Series(3 * np.random.rand(4), index=['a', 'b', 'c', 'd'], name='series')
plt.axis('equal') # 保证长宽相等
plt.pie(s,
explode = [0.1,0,0,0],
labels = s.index,
colors=['r', 'g', 'b', 'c'],
autopct='%.2f%%',
pctdistance=0.6,
labeldistance = 1.2,
shadow = True,
startangle=0,
radius=1.5,
frame=False)
plt.show()

png

直方图

plt.hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None,
histtype=’bar’, align=’mid’, orientation=’vertical’,rwidth=None, log=False, color=None, label=None,
stacked=False, hold=None, data=None, **kwargs)

  • 参数
    • bin:箱子的宽度
    • normed 标准化
    • histtype 风格,bar,barstacked,step,stepfilled
    • orientation 水平还是垂直{‘horizontal’, ‘vertical’}
    • align : {‘left’, ‘mid’, ‘right’}, optional(对齐方式)
    • stacked:是否堆叠
1
2
3
4
5
6
7
8
9
10
11
# 直方图
s = pd.Series(np.random.randn(1000))
s.hist(bins = 20,
histtype = 'bar',
align = 'mid',
orientation = 'vertical',
alpha=0.5,
normed =True)
# 密度图
s.plot(kind='kde',style='k--')
plt.show()
1
2
3
D:\Program Files (x86)\Anaconda3\lib\site-packages\pandas\plotting\_core.py:2477: MatplotlibDeprecationWarning: 
The 'normed' kwarg was deprecated in Matplotlib 2.1 and will be removed in 3.1. Use 'density' instead.
ax.hist(values, bins=bins, **kwds)

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 堆叠直方图

plt.figure(num=1)
df = pd.DataFrame({'a': np.random.randn(1000) + 1, 'b': np.random.randn(1000),
'c': np.random.randn(1000) - 1, 'd': np.random.randn(1000)-2},
columns=['a', 'b', 'c','d'])
df.plot.hist(stacked=True,
bins=20,
colormap='Greens_r',
alpha=0.5,
grid=True)
# 使用DataFrame.plot.hist()和Series.plot.hist()方法绘制

df.hist(bins=50)
# 生成多个直方图
1
2
3
4
5
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F34C1B710>,
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F34C4D2E8>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F34C80898>,
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F34CB2E48>]],
dtype=object)
1
<Figure size 432x288 with 0 Axes>

png

png

散点图

plt.scatter(x, y, s=20, c=None, marker=’o’, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None,
verts=None, edgecolors=None, hold=None, data=None, **kwargs)

参数含义:

  • s:散点的大小
  • c:散点的颜色
  • vmin,vmax:亮度设置,标量
  • cmap:colormap
1
2
3
4
5
6
7
8
9
10
11
plt.figure(figsize=(8,6))

x = np.random.randn(1000)
y = np.random.randn(1000)

plt.scatter(x,y,marker='.',
s = np.random.randn(1000)*100,
cmap = 'Reds_r',
c = y,
alpha = 0.8,)
plt.grid()
1
2
D:\Program Files (x86)\Anaconda3\lib\site-packages\matplotlib\collections.py:857: RuntimeWarning: invalid value encountered in sqrt
scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor

png

1
2
3
4
5
6
7
8
9
10
11
12
# pd.scatter_matrix()散点矩阵
# pd.scatter_matrix(frame, alpha=0.5, figsize=None, ax=None,
# grid=False, diagonal='hist', marker='.', density_kwds=None, hist_kwds=None, range_padding=0.05, **kwds)
# diagonal:({‘hist’, ‘kde’}),必须且只能在{‘hist’, ‘kde’}中选择1个 → 每个指标的频率图
# range_padding:(float, 可选),图像在x轴、y轴原点附近的留白(padding),该值越大,留白距离越大,图像远离坐标原点

df = pd.DataFrame(np.random.randn(100,4),columns = ['a','b','c','d'])
pd.plotting.scatter_matrix(df,figsize=(10,6),
marker = 'o',
diagonal='kde',
alpha = 0.5,
range_padding=0.5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F39EB5828>,
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F3F222278>,
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F3F37E518>,
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F3F391F98>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F3F3AF128>,
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F3F3C5278>,
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F3F3DC3C8>,
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F3F3F3550>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F3F3F3588>,
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F3F41FC18>,
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F3F43C208>,
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F3F4507B8>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F3F466D68>,
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F3F483358>,
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F3F498908>,
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F3F4AFEB8>]],
dtype=object)

png

箱型图

箱型图:又称为盒须图、盒式图、盒状图或箱线图,是一种用作显示一组数据分散情况资料的统计图

包含一组数据的:最大值、最小值、中位数、上四分位数(Q1)、下四分位数(Q3)、异常值

① 中位数 → 一组数据平均分成两份,中间的数

② 下四分位数Q1 → 是将序列平均分成四份,计算(n+1)/4与(n-1)/4两种,一般使用(n+1)/4

③ 上四分位数Q3 → 是将序列平均分成四份,计算(1+n)/4*3=6.75

④ 内限 → T形的盒须就是内限,最大值区间Q3+1.5IQR,最小值区间Q1-1.5IQR (IQR=Q3-Q1)

⑤ 外限 → T形的盒须就是内限,最大值区间Q3+3IQR,最小值区间Q1-3IQR (IQR=Q3-Q1)

⑥ 异常值 → 内限之外 - 中度异常,外限之外 - 极度异常

plt.plot.box(),plt.boxplot()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# plt.plot.box()绘制

fig,axes = plt.subplots(2,1,figsize=(10,6))
df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
color = dict(boxes='DarkGreen', whiskers='DarkOrange', medians='DarkBlue', caps='Gray')
# 箱型图着色
# boxes → 箱线
# whiskers → 分位数与error bar横线之间竖线的颜色
# medians → 中位数线颜色
# caps → error bar横线颜色

df.plot.box(ylim=[0,1.2],
grid = True,
color = color,
ax = axes[0])
1
<matplotlib.axes._subplots.AxesSubplot at 0x24f394cc9b0>

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])

plt.figure(figsize=(10,4))
# 创建图表、数据

f = df.boxplot(sym = 'o', # 异常点形状,参考marker
vert = True, # 是否垂直
whis = 1.5, # IQR,默认1.5,也可以设置区间比如[5,95],代表强制上下边缘为数据95%和5%位置
patch_artist = True, # 上下四分位框内是否填充,True为填充
meanline = False,showmeans=True, # 是否有均值线及其形状
showbox = True, # 是否显示箱线
showcaps = True, # 是否显示边缘线
showfliers = True, # 是否显示异常值
notch = False, # 中间箱体是否缺口
return_type='dict' # 返回类型为字典
)
plt.title('boxplot')

for box in f['boxes']:
box.set( color='b', linewidth=1) # 箱体边框颜色
box.set( facecolor = 'b' ,alpha=0.5) # 箱体内部填充颜色
for whisker in f['whiskers']:
whisker.set(color='k', linewidth=0.5,linestyle='-')
for cap in f['caps']:
cap.set(color='gray', linewidth=2)
for median in f['medians']:
median.set(color='DarkBlue', linewidth=2)
for flier in f['fliers']:
flier.set(marker='o', color='y', alpha=0.5)
# boxes, 箱线
# medians, 中位值的横线,
# whiskers, 从box到error bar之间的竖线.
# fliers, 异常值
# caps, error bar横线
# means, 均值的横线,

png

1
2
3
4
5
6
7
8
9
10
11
# plt.boxplot()绘制
# 分组汇总

df = pd.DataFrame(np.random.rand(10,2), columns=['Col1', 'Col2'] )
df['X'] = pd.Series(['A','A','A','A','A','B','B','B','B','B'])
df['Y'] = pd.Series(['A','B','A','B','A','B','A','B','A','B'])

df.boxplot(by = 'X')
df.boxplot(column=['Col1','Col2'], by=['X','Y'])
# columns:按照数据的列分子图
# by:按照列分组做箱型图
1
2
3
array([<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F3519AD68>,
<matplotlib.axes._subplots.AxesSubplot object at 0x0000024F34B67C88>],
dtype=object)

png

png

坚持原创技术分享,您的支持将鼓励我继续创作!