Python的工具包[2] -> matplotlib图像绘制 -> matplotlib 库及使用总结
matplotlib图像绘制 / matplotlib image description
目录
- 关于matplotlib
- matplotlib库
- 补充内容
- Figure和AxesSubplot的生成方式
- 子图的两种生成方式
- 折线图的绘制
- 柱状图的绘制
- 箱图的绘制
- 散点图的绘制
- 直方图的绘制
- 细节设置
1 关于matplotlib / About matplotlib
Matplotlib 是一个 Python 的 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形。相应内容可参考 matplotlib 官网。
Matplotlib基础知识
1. Matplotlib中的基本图表包括的元素
- x轴和y轴: 水平和垂直的轴线
- x轴和y轴刻度: 刻度标示坐标轴的分隔,包括最小刻度和最大刻度
- x轴和y轴刻度标签: 表示特定坐标轴的值
- 绘图区域: 实际绘图的区域
2. hold属性
- hold属性默认为True,允许在一幅图中绘制多个曲线;将hold属性修改为False,每一个plot都会覆盖前面的plot。
- 但是目前不推荐去动hold这个属性,这种做法(会有警告)。因此使用默认设置即可。
3. 网格线与grid方法
- grid方法: 使用grid方法为图添加网格线
- 设置grid参数(参数与plot函数相同): .lw代表linewidth,线的粗细,.alpha表示线的明暗程度
4. axis方法
- 如果axis方法没有任何参数,则返回当前坐标轴的上下限
5. xlim方法和ylim方法
- 除了plt.axis方法,还可以通过xlim,ylim方法设置坐标轴范围
6. legend
- 注释图标
7. Figure和AxesSubplot
- fig: 一个图表的整体结构,所有需要绘制图像的ax都将置于fig上
- ax: 绘制图像的区域
2 matplotlib库 / matplotlib Library
环境安装:
pip install matplotlib
2.1 常量 / Constants
Pass
2.2 函数 / Function
Pass
2.3 类 / Class
2.3.1 Figure类
类实例化:fig = plt.figure(fig_name, figsize=)
类的功能:用于生成Figure
传入参数: fig_name, figsize
fig_name: str类型,Figure的名称
figsize: tuple类型,确定fig的长宽大小
返回参数: fig
fig: Figure类型,<class 'matplotlib.figure.Figure'>,生成的Figure
2.3.1.1 add_subplot()方法
函数调用:ax = fig.add_subplot(r, c, p)
函数功能:生成绘图区域子图
传入参数: r, c, p
r: int类型,fig区域等分行数
c: int类型,fig区域等分列数
p: int类型,ax所在fig位置处
返回参数: ax
ax: AxesSubplot类型,<class 'matplotlib.axes._subplots.AxesSubplot'>,生成的AxesSubplot
2.3.2 AxesSubplot类
类实例化:ax = plt.subplot(r, c, p) / fig.add_subplot(r, c, p)
类的功能:生成绘图区域
传入参数: r, c, p
r: int类型,fig区域等分行数
c: int类型,fig区域等分列数
p: int类型,ax所在fig位置处
返回参数: ax
ax: AxesSubplot类型,<class 'matplotlib.axes._subplots.AxesSubplot'>,生成的AxesSubplot
Note: 实际上plt.subplot()函数最终调用的也是fig.add_subplot()函数
2.3.2.1 plot()方法
函数调用: ax.plot(x_list, y_list, c=, label=)
函数功能:绘制曲线图
传入参数: x_list, y_list, c, label
x_list: list类型,所有需要绘制的点的横坐标列表
y_list: list类型,所有需要绘制的点的纵坐标列表
c: str/tuple类型,设置线条的颜色,可以使用名称‘red’/缩写‘r’/RGB(1, 0, 0),其中RGB元组中的所有值为x/255,在0-1之间
label: str类型,线条的标签名(在legend上显示)
返回参数: 无
2.3.2.2 bar / barh()方法
函数调用: ax.bar / barh(bar_position, bar_height, bar_width)
函数功能:绘制柱状图(纵向或者横向)
传入参数: bar_position, bar_height, bar_width
bar_position: list类型,所有需要绘制的柱形的横坐标位置列表
bar_height: list类型,所有需要绘制的柱形的高度列表
bar_width: int类型,柱形的宽度
返回参数: 无
2.3.2.3 boxplot()方法
函数调用: ax.boxplot(data)
函数功能:绘制箱图
传入参数: data
data: array/a sequence of vector类型,进行绘图的二维数组,按列分组
返回参数: 无
2.3.2.4 scatter()函数
函数调用: ax.scatter(x, y)
函数功能:绘制散点图
传入参数: x, y
x: list/Series类型,绘制散点图的x坐标集合
y: list/Series类型,绘制散点图的y坐标集合
返回参数: 无
2.3.2.5 hist()方法
函数调用: ax.hist(x, bins=None, range=None)
函数功能:绘制histogram直方图
传入参数: x, bins, range
x: array/a sequence of array类型,数据点集合,不要求同长度
bins: int类型,绘制的直方图分割数量
range: tuple类型,需要绘制直方图的数据范围
返回参数: 无
2.3.2.6 set_xticks / set_yticks()方法
函数调用: ax.set_xticks / set_yticks(posi_list)
函数功能:设置ticks的位置
传入参数: posi_list
posi_list: list类型,各个ticks离原点坐标的距离
返回参数: 无
2.3.2.7 set_xticklabels / set_yticklabels()方法
函数调用: ax.set_xticklabels / set_yticklabels(name_list, rotation=0)
函数功能:设置ticks的名称
传入参数: name_list, rotation
name_list: list类型,各个ticks的名称
rotation: int类型,label顺时针旋转的角度
返回参数: 无
2.3.2.8 set_xlabel / set_ylabel()方法
函数调用: ax.set_xlabel / set_ylabel(name)
函数功能:设置label的名称
传入参数: name
name: str类型,label的名称
返回参数: 无
2.3.2.9 set_title()方法
函数调用: ax.set_title(name)
函数功能:设置title的名称
传入参数: name
name: str类型,title的名称
返回参数: 无
2.3.2.10 set_xlim / set_ylim()方法
函数调用: ax.set_xlim / set_ylim(left, right)
函数功能:设置x/y轴的数值限制
传入参数: left, right
left: int类型,数据的左端极值
right: int类型,数据的右端极值
返回参数: 无
2.3.2.11 tick_params()方法
函数调用: ax.tick_params(axis=‘both’, **kwarge)
函数功能:改变ticks或ticks的显示状态
传入参数: axis, **kwarge
axis: str类型,‘x’/‘y’/‘both’确定目标轴
**kwarge: 传入包括color/bottom/top/left/right/length/width等参数进行设置
返回参数: 无
2.3.2.12 spines属性
属性调用: sp = ax.spines
属性功能:获取所有坐标轴的一个类
属性参数: sp
sp: obj类型,包含所有坐标轴(left, right, bottom, top)信息的类
Note: 对于获取到的sp,可以通过for key, spine in sp.items()获得各个spine,并利用spine的set_visible(False)函数隐藏所有的spine
2.4 模块 / Module
2.4.1 pyplot模块
from matlibplot import pyplot as plt
2.4.1.1 常量
Pass
2.4.1.2 函数
2.4.1.2.1 figure()函数
函数调用:fig = plt.figure(fig_name, figsize=)
函数功能:用于生成Figure
传入参数: fig_name, figsize
fig_name: str类型,Figure的名称
figsize: tuple类型,确定fig的长宽大小
返回参数: fig
fig: Figure类型,<class 'matplotlib.figure.Figure'>,生成的Figure
2.4.1.2.2 subplot()函数
类实例化:ax = plt.subplot(r, c, p)
类的功能:生成绘图区域AxesSubplot
传入参数: r, c, p
r: int类型,fig区域等分行数
c: int类型,fig区域等分列数
p: int类型,ax所在fig位置处
返回参数: ax
ax: AxesSubplot类型,<class 'matplotlib.axes._subplots.AxesSubplot'>,生成的AxesSubplot
Note: 实际上plt.subplot()函数最终调用的也是fig.add_subplot()函数
2.4.1.2.3 subplots()函数
类实例化:fig, ax = plt.subplots(nrows=1, ncols=1, sharex=False, sharey=False)
类的功能:生成图像Figure以及相应数量的绘图区域子图AxesSubplot
传入参数: nrows, ncols, sharex, sharey
nrows: int类型,fig区域等分行数,即nrows个子图在一行
ncols: int类型,fig区域等分列数,即ncols列子图
sharex: bool类型,所有子图是否共享x轴
sharey: bool类型,所有子图是否共享y轴
返回参数: fig, ax
fig: Figure类型,生成的当前Figure
ax: AxesSubplot / list类型,当ax数量大于1时,ax为所有子图组成的ndarray
2.4.1.2.4 plot()函数
函数调用: plt.plot(x_list, y_list, c=, label=)
函数功能:对需要绘制的图像点进行绘制处理(会对ax进行设置)
传入参数: x_list, y_list, c, label
x_list: list类型,所有需要绘制的点的横坐标列表
y_list: list类型,所有需要绘制的点的纵坐标列表
c: str/tuple类型,设置线条的颜色,可以使用名称‘red’/缩写‘r’/RGB(1, 0, 0),其中RGB元组中的所有值为x/255,在0-1之间
label: str类型,线条的标签名(在legend上显示)
返回参数: 无
2.4.1.2.5 xticks / yticks()函数
函数调用: plt.xticks / yticks(loc, name, rotation=0)
函数功能:对最近一个ax设置ticks(轴标记)
传入参数: loc, name, rotation
loc: list类型,包含了每个ticks到零点的距离
name: list类型,每个ticks的名称
rotation: ticks的旋转角度
返回参数: 无
2.4.1.2.6 xlabel / ylabel()函数
函数调用: plt.xlabel / ylabel(name)
函数功能:对最近一个ax设置label名称
传入参数: name
name: str类型,label的名称
返回参数: 无
2.4.1.2.7 title()函数
函数调用: plt.title(name)
函数功能:对最近一个ax设置title名称
传入参数: name
name: str类型,title的名称
返回参数: 无
2.4.1.2.8 legend()函数
函数调用: plt.legend(loc=‘upper right’)
函数功能:对最近一个ax设置legend图例参数
传入参数: loc
loc: str类型,legend所在位置
返回参数: 无
Note:
loc - int or string or pair of floats, default: 'upper right'
The location of the legend. Possible codes are:
=============== =============
Location String Location Code
=============== =============
'best' 0
'upper right' 1
'upper left' 2
'lower left' 3
'lower right' 4
'right' 5
'center left' 6
'center right' 7
'lower center' 8
'upper center' 9
'center' 10
=============== =============
2.4.1.2.9 show()函数
函数调用: plt.show()
函数功能:对所有的Figure类进行图像显示
传入参数: 无
返回参数: 无
3 补充内容 / Complement
3.1 plt函数的作用范围
对于plt函数,其实质依旧是调用了最近的ax的内部函数实现对title/legend/label等的设置,因此直接使用plt函数时需注意代码位置,或者通过特定ax进行直接调用则不需要注意位置问题。
3.2 颜色数组RGB
在matplotlib中的颜色数组RGB内各个值的范围均为0-1,求值的方式为x/255,下面是各个颜色的参考RGB值,除以255后可在matplotlib中使用。
3.3 箱图
箱图boxPlot是一种统计常用的图形,能够充分显示数据分布的状况。下图中包括了中位数,1/4位数,3/4位数的位置,过大或过小的点将以点形式额外表示出来。
4 Figure和AxesSubplot的生成方式
绘制图像的第一步在于生成相应的fig和ax,此处有3种方法用于生成fig与ax
首先导入模块,
from matplotlib import pylab as plt
(1) 利用plt的subplots()函数直接同时生成fig和ax
fig, ax = plt.subplots() print(fig, ax)
(2) 利用plt的figure()函数生成fig,再利用fig的add_subplot()函数生成ax
fig = plt.figure('New_Figure') ax = fig.add_subplot(1, 1, 1) print(fig, ax)
(3) 利用plt的figure()函数生成fig,再利用plt的subplot()函数生成ax
fig = plt.figure('Another_Figure') ax = plt.subplot(1, 1, 1) print(fig, ax)
最后使用show函数可以得到3张图像,分别对应上面的名称
plt.show()
5 子图的两种生成方式
子图的生成方式有以下两种,
- 利用plt.subplots方法直接生成,并从返回的子图列表中获取各个子图实例
- 利用fig实例的fig.add_subplot方法进行添加
# Two ways to create a figure with subplot # First one: subplots # plt.subplots(nrow, ncol) # sharex and sharey decide whether all the subplot should to share the axis label # If multi subplots, ax will be a array contains all subplots fig, ax = plt.subplots(2, 2, sharex=False, sharey=False) ax_1 = ax[0][0] ax_2 = ax[0][1] ax_3 = ax[1][0] ax_4 = ax[1][1] # Second one: use figure fig = plt.figure('figure_name', figsize=(7, 7)) ax_1 = fig.add_subplot(2, 2, 1) ax_2 = fig.add_subplot(2, 2, 2) plt.show()
显示结果
6 折线图的绘制
完整代码
import pandas as pd import numpy as np import matplotlib.pyplot as plt curve = pd.read_csv('curve.csv') print(curve) print('------------') # Change format to datetime format curve['DATE'] = pd.to_datetime(curve['DATE']) print(curve) # matplotlib inline # If plot nothing and show, it will plot and show a blank board # plt.plot() # plt.show() # Similar to pyqtgraph, plot(x_list, y_list) plt.plot(curve['DATE'], curve['VALUE']) # If the tick is too long, use rotation to adjust plt.xticks(rotation=-45) plt.xlabel('Month') plt.ylabel('Rate') plt.title('Unemployment Rate') #plt.show() # Sub figure # figsize decide the size of figure window fig = plt.figure('figure_name', figsize=(7, 7)) # add_subplot(row, column, location) # add_subplot will divide fig into several part(according to row and column) and place the subplot in input location ''' fig divided like that: [1 ... x . . . . . . y ... x*y] ''' # May course some overlap if the shape(row/column) is different ax1 = fig.add_subplot(2, 2, 1) ax2 = fig.add_subplot(2, 2, 2) ax4 = fig.add_subplot(2, 2, 4) ax3 = plt.subplot(2, 2, 3) ax1.plot(np.random.randint(1, 5, 5), np.arange(5)) # Note np.arange(10)*3 will return an array shape(1, 10) with each element * 3 ax2.plot(np.arange(10)*3, np.arange(10)) ax4.plot(np.random.randint(1, 10, 10), np.random.randint(1, 10, 10)) month = curve['DATE'].dt.month value = curve['VALUE'] # If no new fig here, the curve will be plot on the latest fig(ax4 here) fig = plt.figure(figsize=(9, 7)) plt.plot(month[0:6], value[0:6], c='red', label='first half year') # c='r'/c=(1, 0, 0) plt.plot(month[6:12], value[6:12], c='blue', label='second half year') # If not call legend function, the label would not show # loc='best' will place the label in a best location ''' loc : int or string or pair of floats, default: 'upper right' The location of the legend. Possible codes are: =============== ============= Location String Location Code =============== ============= 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 =============== ============= ''' plt.legend(loc='best') plt.xlabel('Month') plt.ylabel('Rate') plt.title('My rate curve') plt.show()
分段解释
首先导入需要用到的 numpy 和 pandas 模块,读取所需要的数据,转变为指定的时间格式,
import pandas as pd import numpy as np import matplotlib.pyplot as plt curve = pd.read_csv('curve.csv') print(curve) print('------------') # Change format to datetime format curve['DATE'] = pd.to_datetime(curve['DATE']) print(curve)
输出结果如下
DATE VALUE A B C D E 0 1/1/1948 3.4 2.400000 4.50 2.400000 2.200000 5.60 1 2/1/1948 3.8 2.700000 3.50 8.800000 3.400000 4.20 2 3/1/1948 4.2 2.500000 4.60 4.300000 4.100000 7.30 3 4/1/1948 5.1 2.633333 4.30 7.066667 5.133333 7.40 4 5/1/1948 1.9 2.683333 4.35 8.016667 6.083333 8.25 5 6/1/1948 2.4 2.733333 4.40 8.966667 7.033333 9.10 6 7/1/1948 3.2 2.783333 4.45 9.916667 7.983333 9.95 7 8/1/1948 4.4 2.833333 4.50 10.866667 8.933333 10.80 8 9/1/1948 5.2 2.883333 4.55 11.816667 9.883333 11.65 9 10/1/1948 3.2 2.933333 4.60 12.766667 10.833333 12.50 10 11/1/1948 2.1 2.983333 4.65 13.716667 11.783333 13.35 11 12/1/1948 1.2 3.033333 4.70 14.666667 12.733333 14.20 12 1/1/1949 5.5 3.083333 4.75 15.616667 13.683333 15.05 13 2/1/1949 3.2 3.133333 4.80 16.566667 14.633333 15.90 14 3/1/1949 6.2 3.183333 4.85 17.516667 15.583333 16.75 15 4/1/1949 1.3 3.233333 4.90 18.466667 16.533333 30.00 ------------ DATE VALUE A B C D E 0 1948-01-01 3.4 2.400000 4.50 2.400000 2.200000 5.60 1 1948-02-01 3.8 2.700000 3.50 8.800000 3.400000 4.20 2 1948-03-01 4.2 2.500000 4.60 4.300000 4.100000 7.30 3 1948-04-01 5.1 2.633333 4.30 7.066667 5.133333 7.40 4 1948-05-01 1.9 2.683333 4.35 8.016667 6.083333 8.25 5 1948-06-01 2.4 2.733333 4.40 8.966667 7.033333 9.10 6 1948-07-01 3.2 2.783333 4.45 9.916667 7.983333 9.95 7 1948-08-01 4.4 2.833333 4.50 10.866667 8.933333 10.80 8 1948-09-01 5.2 2.883333 4.55 11.816667 9.883333 11.65 9 1948-10-01 3.2 2.933333 4.60 12.766667 10.833333 12.50 10 1948-11-01 2.1 2.983333 4.65 13.716667 11.783333 13.35 11 1948-12-01 1.2 3.033333 4.70 14.666667 12.733333 14.20 12 1949-01-01 5.5 3.083333 4.75 15.616667 13.683333 15.05 13 1949-02-01 3.2 3.133333 4.80 16.566667 14.633333 15.90 14 1949-03-01 6.2 3.183333 4.85 17.516667 15.583333 16.75 15 1949-04-01 1.3 3.233333 4.90 18.466667 16.533333 30.00
绘制折线图
# matplotlib inline # If plot nothing and show, it will plot and show a blank board # plt.plot() # plt.show() # Similar to pyqtgraph, plot(x_list, y_list) plt.plot(curve['DATE'], curve['VALUE']) # If the tick is too long, use rotation to adjust plt.xticks(rotation=-45) plt.xlabel('Month') plt.ylabel('Rate') plt.title('Unemployment Rate') #plt.show()
显示图形
接着绘制带有子图的折线图
其中子图的顺序如代码中注释所示
# Sub figure # figsize decide the size of figure window fig = plt.figure('figure_name', figsize=(7, 7)) # add_subplot(row, column, location) # add_subplot will divide fig into several part(according to row and column) and place the subplot in input location ''' fig divided like that: [1 ... x . . . . . . y ... x*y] ''' # May course some overlap if the shape(row/column) is different ax1 = fig.add_subplot(2, 2, 1) ax2 = fig.add_subplot(2, 2, 2) ax4 = fig.add_subplot(2, 2, 4) ax3 = plt.subplot(2, 2, 3) ax1.plot(np.random.randint(1, 5, 5), np.arange(5)) # Note np.arange(10)*3 will return an array shape(1, 10) with each element * 3 ax2.plot(np.arange(10)*3, np.arange(10)) ax4.plot(np.random.randint(1, 10, 10), np.random.randint(1, 10, 10))
显示图形
最后,尝试将两条折线绘制在同一个图上,
Note: 第四行生成了一个新的fig,如果此处没有新生成一个fig,则图像会被显示在最近的一个fig上(此处为之前的ax4)
month = curve['DATE'].dt.month value = curve['VALUE'] # If no new fig here, the curve will be plot on the latest fig(ax4 here) fig = plt.figure(figsize=(9, 7)) plt.plot(month[0:6], value[0:6], c='red', label='first half year') # c='r'/c=(1, 0, 0) plt.plot(month[6:12], value[6:12], c='blue', label='second half year') # If not call legend function, the label would not show # loc='best' will place the label in a best location ''' loc : int or string or pair of floats, default: 'upper right' The location of the legend. Possible codes are: =============== ============= Location String Location Code =============== ============= 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 =============== ============= ''' plt.legend(loc='best') plt.xlabel('Month') plt.ylabel('Rate') plt.title('My rate curve') plt.show()
显示图形
7 柱状图的绘制
完整代码
import pandas as pd import matplotlib.pyplot as plt import numpy as np curve = pd.read_csv('curve.csv') cols = ['A', 'B', 'C', 'D', 'E'] para = curve[cols] print(para) print(para[:1]) print('-----------') # ix function can fetch the data in certain position by index # ix[row, column], row/column can be a number/list/key_list # Bar height decide the height of bar graph bar_height = para.ix[0, cols].values # para.ix[0, cols] type is Series # Bar position decide the x distance to base point bar_position = np.arange(5) + 1 # subplots function return a figure and only one subplot # fig to set figure style, ax(axis) for graph draw fig, ax = plt.subplots() # bar(position_list, height_list, width_of_bar) ax.bar(bar_position, bar_height, 0.3) # Use barh to create a horizonal bar figure ax.barh(bar_position, bar_height, 0.3) # Set position of ticks ax.set_xticks(range(1, 6)) # Set x tick labels name and rotation ax.set_xticklabels(cols, rotation=45) # Set x/y label name ax.set_xlabel('Type') ax.set_ylabel('Rate') ax.set_title('This is a test figure')
分段解释
首先导入各个模块,并读取数据,
import pandas as pd import matplotlib.pyplot as plt import numpy as np curve = pd.read_csv('curve.csv') cols = ['A', 'B', 'C', 'D', 'E'] para = curve[cols] print(para) print(para[:1]) print('-----------')
输出结果为
A B C D E 0 2.400000 4.50 2.400000 2.200000 5.60 1 2.700000 3.50 8.800000 3.400000 4.20 2 2.500000 4.60 4.300000 4.100000 7.30 3 2.633333 4.30 7.066667 5.133333 7.40 4 2.683333 4.35 8.016667 6.083333 8.25 5 2.733333 4.40 8.966667 7.033333 9.10 6 2.783333 4.45 9.916667 7.983333 9.95 7 2.833333 4.50 10.866667 8.933333 10.80 8 2.883333 4.55 11.816667 9.883333 11.65 9 2.933333 4.60 12.766667 10.833333 12.50 10 2.983333 4.65 13.716667 11.783333 13.35 11 3.033333 4.70 14.666667 12.733333 14.20 12 3.083333 4.75 15.616667 13.683333 15.05 13 3.133333 4.80 16.566667 14.633333 15.90 14 3.183333 4.85 17.516667 15.583333 16.75 15 3.233333 4.90 18.466667 16.533333 30.00 A B C D E 0 2.4 4.5 2.4 2.2 5.6 -----------
随后根据数据绘制柱状图
# ix function can fetch the data in certain position by index # ix[row, column], row/column can be a number/list/key_list # Bar height decide the height of bar graph bar_height = para.ix[0, cols].values # para.ix[0, cols] type is Series # Bar position decide the x distance to base point bar_position = np.arange(5) + 1 # subplots function return a figure and only one subplot # fig to set figure style, ax(axis) for graph draw fig, ax = plt.subplots() # bar(position_list, height_list, width_of_bar) ax.bar(bar_position, bar_height, 0.3) # Use barh to create a horizonal bar figure ax.barh(bar_position, bar_height, 0.3) # Set position of ticks ax.set_xticks(range(1, 6)) # Set x tick labels name and rotation ax.set_xticklabels(cols, rotation=45) # Set x/y label name ax.set_xlabel('Type') ax.set_ylabel('Rate') ax.set_title('This is a test figure')
得到图形
8 箱图的绘制
import pandas as pd import matplotlib.pyplot as plt import numpy as np curve = pd.read_csv('curve.csv') cols = ['A', 'B', 'C', 'D', 'E'] fig, ax = plt.subplots() ax.boxplot(curve[cols].values) # curve[cols].values is ndarray print(curve[cols].values) plt.show()
输出数据
[[ 2.4 4.5 2.4 2.2 5.6 ] [ 2.7 3.5 8.8 3.4 4.2 ] [ 2.5 4.6 4.3 4.1 7.3 ] [ 2.63333333 4.3 7.06666667 5.13333333 7.4 ] [ 2.68333333 4.35 8.01666667 6.08333333 8.25 ] [ 2.73333333 4.4 8.96666667 7.03333333 9.1 ] [ 2.78333333 4.45 9.91666667 7.98333333 9.95 ] [ 2.83333333 4.5 10.86666667 8.93333333 10.8 ] [ 2.88333333 4.55 11.81666667 9.88333333 11.65 ] [ 2.93333333 4.6 12.76666667 10.83333333 12.5 ] [ 2.98333333 4.65 13.71666667 11.78333333 13.35 ] [ 3.03333333 4.7 14.66666667 12.73333333 14.2 ] [ 3.08333333 4.75 15.61666667 13.68333333 15.05 ] [ 3.13333333 4.8 16.56666667 14.63333333 15.9 ] [ 3.18333333 4.85 17.51666667 15.58333333 16.75 ] [ 3.23333333 4.9 18.46666667 16.53333333 30. ]]
显示图形
9 散点图的绘制
import matplotlib.pyplot as plt import numpy as np import pandas as pd curve = pd.read_csv('curve.csv') fig, ax = plt.subplots() # scatter(x, y) x for x axis para list/Series, y for y axis para list/Series ax.scatter(curve['A'], curve['B']) plt.show()
输出图形
10 直方图的绘制
import pandas as pd import matplotlib.pyplot as plt import numpy as np curve = pd.read_csv('curve.csv') cols = ['A', 'B', 'C', 'D', 'E'] # value_counts function will return the number of each value print(curve['C'].value_counts()) fig, ax = plt.subplots() # hist(Series, range=, bins=) # Series is the data to be plotted, range is the plot range, bins is the number of plot hists in range ax.hist(curve['C'], range=(1,20), bins=20) # Set the x/y axis limit range ax.set_xlim(0, 20) ax.set_ylim(0, 5) plt.show()
输出结果
15.616667 1 18.466667 1 12.766667 1 8.800000 1 2.400000 1 16.566667 1 9.916667 1 8.016667 1 10.866667 1 17.516667 1 7.066667 1 4.300000 1 11.816667 1 8.966667 1 14.666667 1 13.716667 1 Name: C, dtype: int64
显示图形
11 细节设置
利用matplotlib还可以对图形的细节进行相应的设置
import pandas as pd import matplotlib.pyplot as plt import numpy as np curve = pd.read_csv('curve.csv') fig, ax = plt.subplots() # Hide the tick params ax.tick_params(bottom='off', top='off', left='off', right='off') # Hide spine print(type(ax.spines)) for key, spine in ax.spines.items(): print(key, spine) spine.set_visible(False) # Set the color, (R, G, B) the value should be between (0, 1) color_dark_blue = (0/255, 107/255, 164/255) color_orange = (255/255, 128/255, 14/255) ax.plot(curve['A'], curve['B'], c=color_dark_blue, label='AB', linewidth=7) ax.plot(curve['C'], curve['D'], c=color_orange, label='CD', linewidth=7) plt.legend(loc='upper right') plt.show()
输出图形
相关阅读
1. numpy 的使用
2. pandas 的使用
Python的工具包[2] -> matplotlib图像绘制 -> matplotlib 库及使用总结的更多相关文章
- Python的工具包[0] ->; numpy科学计算 ->; numpy 库及使用总结
NumPy 目录 关于 numpy numpy 库 numpy 基本操作 numpy 复制操作 numpy 计算 numpy 常用函数 1 关于numpy / About numpy NumPy系统是 ...
- Python的工具包[1] ->; pandas数据预处理 ->; pandas 库及使用总结
pandas数据预处理 / pandas data pre-processing 目录 关于 pandas pandas 库 pandas 基本操作 pandas 计算 pandas 的 Series ...
- 【Python】一份非常好的Matplotlib教程
Matplotlib 教程 本文为译文,原文载于此,译文原载于此.本文欢迎转载,但请保留本段文字,尊重作者和译者的权益.谢谢.: ) 介绍 Matplotlib 可能是 Python 2D-绘图领域使 ...
- Python中的Numpy、SciPy、MatPlotLib安装与配置
Python安装完Numpy,SciPy和MatplotLib后,可以成为非常犀利的科研利器.网上关于这三个库的安装都写得非常不错,但是大部分人遇到的问题并不是如何安装,而是安装好后因为配置不当,在使 ...
- Python 数据可视化 -- pillow 处理图像
Python 图像库(Python Image Library,PIL)为 Python 提供了图像处理能力. PIL 官网:http://www.pythonware.com/products/pi ...
- Matplotlib学习---用matplotlib画箱线图(boxplot)
箱线图通过数据的四分位数来展示数据的分布情况.例如:数据的中心位置,数据间的离散程度,是否有异常值等. 把数据从小到大进行排列并等分成四份,第一分位数(Q1),第二分位数(Q2)和第三分位数(Q3)分 ...
- python机器学习工具包
1. scikit-learn: Machine Learning in Python scikit-learn是一个基于NumPy, SciPy, Matplotlib的开源机器学习工具包,主要涵盖 ...
- python K-means工具包初解
近期数据挖掘实验,写个K-means算法,写完也不是非常难,写的过程中想到python肯定有包,尽管师兄说不让用,只是自己也写完了,而用包的话,还不是非常熟,略微查找了下资料,学了下.另外,自己本身写 ...
- matplotlib 可视化 —— 定制 matplotlib
1. matplotlibrc 文件 matplotlib使用matplotlibrc [matplotlib resource configurations] 配置文件来自定义各种属性,我们称之为 ...
随机推荐
- 01 LabVIEW的类中各个Scope的范围
范例地址: D:\Program Files (x86)\National Instruments\LabVIEW 2015\examples\Object-Oriented Programming\ ...
- Elasticsearch Javascript API增删改查
查询 根据索引.类型.id进行查询: client.get({ index:'myindex', type:'mytype', id:1 },function(error, response){// ...
- C语言学习常识
开发环境 学习C语言,在mac os x上,我们选用的开发工具是x-code:而在Windows上,我们一般用微软提供的vc6.0:此外还有很多编辑器内置了或者支持下载C语言的编译器插件.所以,我们可 ...
- Reveal-Plugin-for-Xcode 自动结合 Reveal 进行 UI 分析
下载地址:https://github.com/shjborage/Reveal-Plugin-for-Xcode 还记得之前我们如何使用 Reveal UI 分析工具进行实时查看 UI 的结构吗?如 ...
- Win7下判断当前进程是否以管理员身份运行
判断当前程序是否以管理员身份运行,代码如下: #include <iostream> #include <windows.h> using namespace std; // ...
- Hibernate HQL基础 使用参数占位符
在HQL中有两种方法实现使用参数占用符 1.使用? 使用?设置参数占位符,之后通过setString()和setInteger()等方法为其赋值.如: Query query = session.cr ...
- dapper+linq+json+ztree构建树
dapper获取实体的集合 /// <summary> /// 获取表tb_sys_zhuowei所有数据 /// </summary> public IEnumerable& ...
- 报错 BeanFactory not initialized or already closed - call &#39;refresh&#39; before accessing beans via the ApplicationContext 的解决方法
这个普遍是因为tomcat 的 jar包问题,重新导入一下tomcat的jar包就OK了.
- redis 系列25 哨兵Sentinel (高可用演示 下)
一. Sentinel 高可用环境准备 1.1 Sentinel 集群环境 环境 说明 操作系统版本 CentOS 7.4.1708 IP地址 172.168.18.200 网关Gateway 1 ...
- 《C#图解教程》一览
本书针对编程新手和中级水平的程序员.笔者尽力专注 C# 语言本身,详尽深入地描述语言及各部分.少涉及 .NET 和相关编程实践.本书写作过程中,笔者始终坚持确保内容简洁性的同时又能透彻地讲解这门语言. ...