python入门基础代码图-Python Matplotlib绘图基础知识代码解析

1.Figure和Subplot

import numpy as np

import matplotlib.pyplot as plt

#创建一个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上绘制

#'k--'为线型选项,绘制黑色虚线

plt.plot(np.random.randn(50).cumsum(), 'k--')

print(type(ax1))#

#直接调用它们的实例方法就可以在其他格子绘图

_ = ax1.hist(np.random.randn(100), bins=20, color='k', alpha=0.3)

ax2.scatter(np.arange(30), np.arange(30) + 3 * np.random.randn(30))

plt.show()

fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)#创建一个新的Figure,并返回一个已创建subplot对象的NumPy数组

#可以索引axes[0,1],axes[0][1]

'''

plt.subplots的选项

nrows:subplot的行数

ncols:subplot的列数

sharex:所有subplot应该使用相同的x轴刻度(调节xlim将会影响所有subplot)

sharey:所有subplot应该使用相同的y轴刻度(调节ylim将会影响所有subplot)

subplot_kw:用于创建各subplot的关键字字典

**fig_kw:创建figure时其他关键字,如plt.subplots(2,2,figsize=(8,6))

'''

for i in range(2):

for j in range(2):

axes[i,j].hist(np.random.randn(500),bins=50, color='k',alpha=0.5)

#调整subplot周围间距

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

plt.subplots_adjust(wspace=0, hspace=0)

plt.show()

2.颜色、标记和线型

#ax.plot(x,y,'g--')

#ax.plot(x, y, linestyle='--', color='g')

#plt.plot(np.random.randn(30).cumsum(), 'ko--')

#plt.plot(np.random.randn(30).cumsum(), color='k', linestyle='dashed', marker='o')

#线型图中,非实际数据点默认是按线性方式插值的,可以通过drawstyle选项修改

data = np.random.randn(30).cumsum()

plt.plot(data, 'k--', label='Defalt')

plt.plot(data, 'k-', drawstyle='steps-post', label='steps-post')

plt.legend(loc='best')

3.刻度、标签和图例

xlim,xticks,xticklabels之类的方法。它们分别控制图表的范围、刻度位置、刻度标签等。

其使用方式有以下两种:

调用时不带参数,则返回当前参数值。plt.xlim()

调用时带参数,则设置参数值。plt.xlim([0,10])

这些方法对当前或最近创建的AxesSubplot起作用

对应在subplot对象上的两个方法,如ax.get_xlim和ax.set_xlim

3.1.设置标题、轴标签、刻度以及刻度标签

fig = plt.figure()

ax = fig.add_subplot(1,1,1)

ax.plot(np.random.randn(1000).cumsum())

#改变X轴的刻度,最简单的方法是使用set_xticks和set_xticklabels。

#前者告诉刻度放在数据范围中的哪些位置,默认情况下,这些位置是刻度标签,可以用set_xticklabels设置。

a=ax.set_xticks([0,250,500,750,1000])

b=ax.set_xticklabels(['one','two','three','four','five'],rotation=30,fontsize='small')

ax.set_xlabel('Stages')

plt.show()

3.2.添加图例(legend)、注解以及在Subplot上绘图

两种方式,最简单的是在添加subplot的时候传入label参数

fig = plt.figure()

ax = fig.add_subplot(1,1,1)

ax.plot(np.random.randn(1000).cumsum(), 'k', label='one')

ax.plot(np.random.randn(1000).cumsum(), 'k--', label='two')

ax.plot(np.random.randn(1000).cumsum(), 'k.', label='three')

ax.legend(loc='best')

#loc表示将图例放在哪

#从图例中去除一个或多个元素,不传入label或label='_nolegend_'即可

#注解以及在Subplot上绘图

#注解可以通过text,arrow和annotate等函数进行添加。

#text可以将文本绘制在图标的指定坐标(x,y),还可以加上一些自定义格式

#ax.text(x ,y, 'Hello world!',family='monosapce',fontsize=10)

plt.show()

3.3.将图表保存到文件

plt.savefig('filepath.svg')

plt.savefig('filepath.svg', dpi=400,bbox_inches='tight')

Figure.savefig参数

fname:路径,包含设置文件格式(如.pdf等)

dpi:图像分辨率,默认100

facecolor、edgecolor:图像背景色,默认为'w'(白色)

format:显示设置文件格式

bbox_inches:图像需要保存的部分。'tight',将尝试剪除图像周围的空白部分

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。