Python进阶 -- 1. matplotlib

来源:互联网 发布:瑜伽软件哪个好用 编辑:程序博客网 时间:2024/06/10 09:31

通过安装Anaconda3,使用matplotlib库



0. 基本绘画设置
(1). Figure和Subplot
matplotlib的图像都位于Figure对象中,你可以用plt.figure创建一个新的Figure.

#这时会弹出一个空窗fig = plt.figure()

但是不能通过空Figure绘图,必须用add_subplot创建一个或多个subplot才行

#这条代码的意思是:图像应该是2X2的,且当前选中的是第一个ax1 = fig.add_subplot(2,2,1)#再绘制两个ax2 = fig.add_subplot(2,2,2)ax3 = fig.add_subplot(2,2,3)

此时绘图,就会在subplot上进行绘制
例如:

from numpy.random import randnplt.plot(randn(50).cumsum(), 'k--')#'k--'是一个线型选项,用于告诉matplotlib绘制黑色虚线图。

别一种更为方便的方法,可以创建一个新的Figure,并返回一个含有已创建subplot对象的NumPy数组:

#创建了一个两行,三列的区域fig, axes = plt.subplots(2,3)

这里写图片描述

(2). 调整subplot周围的间距
默认情况下,matplotlib会在subplot外围留下一定的边距,并在subplot之间留下一定的间距。
利用subplots_adjust方法可以调整间距

fig, axes = plt.subplots(2,2, sharex=True, sharey=True)for i in range(2):    for j in range(2):        axes[i,j].hist(randn(500), bins=50, color='k', alpha=0.5)plt.subplots_adjust(wspace=0, hspace=0)

这里写图片描述

(3). 颜色、标记和线型
根据x,y绘制绿色虚线

ax.plot(x, y, 'g--')#与下面设置是一样的ax.plot(x, y, linestyle='--', color='g')

线型图可以加上一些标记,来强调实际的点

plt.plot(randn(30).cumsum(), 'ko--')#等价于plt.plot(randn(30).cumsum(), color='k', linestyle='dashed', marker='o')

(4). 刻度、标签和图例
添加刻度和标签

fig = plt.figure()ax = fig.add_subplot(1,1,1)ax.plot(randn(1000).cumsum())#修改X轴的刻度#刻度放在哪些位置ticks = ax.set_xticks([0,250,500,750,1000])#也可以将其他值用作标签labels = ax.set_xticklabels(['one','two','three','four','five'], rotation=30, fontsize='small')#为X轴设置一个名称ax.set_title('My first matplotlib plot')#设置一个标题ax.set_xlabel('Stages')

这里写图片描述

添加图例:

fig = plt.figure()ax = fig.add_subplot(1,1,1)ax.plot(randn(1000).cumsum(), 'k', label='one')ax.plot(randn(1000).cumsum(), 'k--', label='two')ax.plot(randn(1000).cumsum(), 'k.', label='three')ax.legend(loc='best')

这里写图片描述



1. 绘制简单的折线图

(1). 函数plot()
列表传递给这个函数,这个函数将尝试根据这些数字绘制出有意义的图形。

import matplotlib.pyplot as pltsquares = [1, 4, 9, 16, 25]plt.plot(squares)plt.show()

(2). 修改标签文字和线条粗细

import matplotlib.pyplot as pltsquares = [1, 4, 9, 16, 25]#参数linewidth 决定了plot() 绘制的线条的粗细plt.plot(squares, linewidth=5)# 设置图表标题, 并给坐标轴加上标签plt.title("Square Numbers", fontsize=24)plt.xlabel("Value", fontsize=14)plt.ylabel("Square of Value", fontsize=14)# 设置刻度标记的大小plt.tick_params(axis='both', labelsize=14)plt.show()

(3). 校正图形

  • 当你向plot() 提供一系列数字时, 它假设第一个数据点对应的 x 坐标值为0, 但我们的第一个点对应的 x 值为1。
  • 为改变这种默认行为, 我们可以给plot() 同时提供输入值和输出值:
input_values = [1, 2, 3, 4, 5]squares = [1, 4, 9, 16, 25]plt.plot(input_values, squares, linewidth=5)


2. 绘制绘制散点图
(1). 使用scatter() 绘制散点图并设置其样式

import matplotlib.pyplot as pltplt.scatter(2, 4)plt.show()

(2).使用scatter() 绘制一系列点

import matplotlib.pyplot as pltx_values = [1, 2, 3, 4, 5]y_values = [1, 4, 9, 16, 25]#并使用实参s 设置了绘制图形时使用的点的尺寸plt.scatter(x_values, y_values, s=100)plt.show()

(3).删除数据点的轮廓
可在调用scatter() 时传递实参edgecolor=’none’

plt.scatter(x_values, y_values, edgecolor='none', s=40)

(4).自定义颜色
要修改数据点的颜色, 可向scatter() 传递参数c , 并将其设置为要使用的颜色的名称,

plt.scatter(x_values, y_values, c='red', edgecolor='none', s=40)

(5).使用颜色映射
颜色映射 ( colormap) 是一系列颜色, 它们从起始颜色渐变到结束颜色。

import matplotlib.pyplot as pltx_values = list(range(1001))y_values = [x**2 for x in x_values]plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, edgecolor='none', s=40)# 设置每个坐标轴的取值范围plt.axis([0, 1100, 0, 1100000])plt.show()
  • 我们将参数c 设置成了一个 y 值列表, 并使用参数cmap 告诉pyplot 使用哪个颜色映射。
  • 这些代码将 y值较小的点显示为浅蓝色, 并将 y 值较大的点显示为深蓝色.

(6).自动保存图表
要让程序自动将图表保存到文件中, 可将对plt.show() 的调用替换为对plt.savefig() 的调用

plt.savefig('squares_plot.png', bbox_inches='tight')
  • 第一个实参指定要以什么样的文件名保存图表, 这个文件将存储到scatter_squares.py所在的目录中;
  • 第二个实参指定将图表多余的空白区域裁剪掉。 如果要保留图表周围多余的空白区域, 可省略这个实参。

(7). 隐藏坐标轴

plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)

(8). 调整尺寸以适合屏幕
函数figure() 用于指定图表的宽度、 高度、 分辨率和背景色。
你需要给形参figsize 指定一个元组, 向matplotlib指出绘图窗口的尺寸, 单位为英寸。
plt.figure(figsize=(10, 6))



3. 随机漫步
choice()函数

#choice([0, 1, 2, 3, 4]) 随机地选择一个0~4之间的整数x_distance = choice([0, 1, 2, 3, 4])

range()函数
返回一系列连续增加的整数

randint()函数
返回一个1和面数之间的随机数

0 0
原创粉丝点击