Matplotlib画图常用方法总结(全)

Matplotlib画图指南

常见的python的matplotlib 的画图的方法,画散点图,曲线图,子图,以及子图的布局,间距等。

1:首先导入包,因为画图常用的数据类型我们需要导入包numpy

import numpy as np

import matplotlib.pyplot as plt

2:创建新图

fig=plt.figure()

          Fig=plt.figure(1)

       使用add_subplot创建多个子图 subplot

       Ax1=fig.add_subpot(2,2,1)

新图和子图之间的关系:

3:使用plot()函数画图

plot()画曲线图,可设置点的格式,线的格式。

Scatter()划散点图,可以设置散点的样式。

matplotlib.pyplot.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 

基本的x y参数,还有csalphamarkerc就是为点指定的颜色数组,s是点的面积大小,alpha是点的颜色的透明度,marker是指定点标记的形状,linewidths为线宽。在例子里指定透明度为0.5c表示颜色常见的颜色为 ['r','y','g','b','r','y','g','b','r'

S[1,2,3,4,5…100]表示形状的面积。我们要改变的是marker的值,marker有很多值可供选择,下表展示了在例子代码的基础上,改变marker的值后的效果:

·        使用HTML十六进制字符串 color='eeefff' 使用合法的HTML颜色名字(’red’,’chartreuse’等)。

·        也可以传入一个归一化到[0,1]RGB元祖。 color=(0.3,0.3,0.4)

用来该表线条的属性

线条风格linestylels

描述

线条风格linestylels

描述

‘-‘

实线

‘:’

虚线

 

‘–’

破折线

‘None’,’ ‘,’’

什么都不画

 

‘-.’

联合使用‘颜色标记线条属性’'bs-.','go-'

 

  

plt.plot(t,t, 'r--', t, t**2, 'bs', t, t**3, 'g^'),叠加图

plot(X,S, color="red", linewidth=2.5, linestyle="-", label="sine")

plot(X,C, color="blue", linewidth=2.5, linestyle='-', label='cosine')

简写版:

plt.plot([1,2,3],[1,2,3], 'go-', label='line 1', linewidth=2)

plt.scatter(x,y, s=area, c=colors, alpha=0.5, marker=(9, 3, 30))

也可以不断地修改颜色和值的大小和形状样式

 

5:细化横轴和纵轴的设置,设置横轴、纵轴的界限以及标注

plt.xlim(X.min(),X.max())

plt.ylim(y.min(),y.max())

或者

plt.axis([X.min(),X.max(),y.min(), y.max()])

6:设置轴记号

plt.xticks()/plt.yticks()设置轴记号

例如:xticks([-np.pi, -np.pi/2, 0, np.pi/2,np.pi],

[r'$-\pi$',r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])

yticks([-1,0, +1],[r'$-1$', r'$0$', r'$+1$'])

 

plt.xticks([1,2,3,…])会根据设置来显示标记

没有plt.xticks([1,2,3,…])会根据具体情况来自动设置标记(比较好,省事)。

7:plt.legend()添加图例

Legend(loc):使用loc参数

plt.legend(loc='lower left')

0: ‘best'

1: ‘upper right'

2: ‘upper left'

3: ‘lower left'

4: ‘lower right'

5: ‘right'

6: ‘center left'

7: ‘center right'

8: ‘lower center'

9: ‘upper center'

10: ‘center'

plt.legend(loc='best',frameon=False) #去掉图例边框,推荐使用,效果比较美观。

plt.legend(loc='best',edgecolor='blue') #设置图例边框颜色

plt.legend(loc='best',facecolor='blue') #设置图例背景颜色,若无边框,参数无效

 

用法1

plot(X, C, color="blue", linewidth=2.5,linestyle="-", label="cosine")

plot(X, S, color="red", linewidth=2.5,linestyle="-", label="sine")

legend(loc='upper left')

用法2plt.plot(x, y, color="red",linewidth=2.5, linestyle="-")

        Plt.legend('图例名',loc='best',frameon=False)

用法3;显示多个图例

p1, = plt.plot([1,2,3])

p2, = plt.plot([3,2,1])

l1 = plt.legend([p2, p1], ["line 2", "line1"], loc='upper left')

8:添加文字说明

·        text()可以在图中的任意位置添加文字,并支持LaTex语法

·        xlable(), ylable()用于添加x轴和y轴标签

·        title()用于添加图的题目

  plt.xlabel('Smarts')    plt.ylabel('Probability')

#添加标题  plt.title('Histogram of IQ')

#添加文字  plt.text(60, .025, r'$\mu=100,\ \sigma=15$')

9:让图片能够正常显示负数和中文:

import matplotlib as mpl

mpl.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签

mpl.rcParams['axes.unicode_minus']=False#用来正常显示负号

 

plt.plot(a,'b.',markersize=10, label=u'真')

中文使用之前加u data[u’身高’]

附加的设置:

1:plt.figure(figsize=(12,16)),设置图片的大小

2:调整子图的距离。

plt.tight_layout()#调整每隔子图之间的距离。自动调整,有时候效果也不太好。

调整子图之间的边距;

plt.subplots_adjust(left=None, bottom=None, right=None, top=None,

                       wspace=None, hspace=None)

left  = 0.125  # the left side of thesubplots of the figure

right = 0.9    # the right side of the subplots of the figure

bottom = 0.1   # the bottom of the subplots of the figure

top = 0.9      # the top of the subplots of the figure

wspace = 0.2   # the amount of width reserved for blank space between subplots,

            # expressed as a fraction of the average axis width

hspace = 0.2   # the amount of height reserved for white space between subplots,

               # expressed as a fraction of the average axis height

3:子图的布局

首先按照(2,2)划分,第一个图为(2,2,1)和(2,2,2)

然后把下面两个图合成一个,则上面两个图为(2,1,2)

 

最后:举一个栗子

import matplotlib as mpl
mpl.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
mpl.rcParams['axes.unicode_minus']=False #用来正常显示负号
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1,10)
y = x
fig = plt.figure(1)
ax1 = fig.add_subplot(211)
ax1.set_title('图一的第一张子图')
plt.xlabel('X1')
plt.ylabel('Y1')
sValue = x*10
ax1.scatter(x,y,s=sValue,c='r',marker='1')
plt.axis([0, 10,0,10])
ax1.legend('图例1.1')

ax2 = fig.add_subplot(212)
ax2.set_title('图一的第二张子图')
plt.xlabel('X12')
plt.ylabel('Y12')
plt.plot(x, y, 'go-')
plt.axis([0, 10,0,10])
ax2.legend('图例1.2')

x = np.arange(1,100)
y = x
fig = plt.figure(2)
ax1 = fig.add_subplot(211)
ax1.set_title('图2的第一张子图')
plt.xlabel('X1')
plt.ylabel('Y1')
sValue = x*10
colo=['r','y','g','b','r','y','g','b','r','m']
ax1.scatter(x,y,s=sValue ,c=colo)
plt.axis([0, 10,0,10])
ax1.legend('图例1.1')
ax2 = fig.add_subplot(212)
#设置标题
ax2.set_title('图二的第二张子图')
#设置X轴标签
plt.xlabel('X12')
#设置Y轴标签
plt.ylabel('Y12')
#画折线图
plt.plot(x, y, color="red", linewidth=2.5, linestyle="-")
plt.axis([0, 100,0,100])
#设置图标
ax2.legend('图例1.2',loc='best',frameon=False)
plt.show()

 

 

 

   

猜你喜欢

转载自blog.csdn.net/weixin_40637396/article/details/80859180