python包matplotlib绘图基础入门

34 篇文章 5 订阅
27 篇文章 1 订阅

1、matplotlib

matplotlib是numpy的扩展,可以实现python框架下的可视化,类似MATLAB的图像可视化。
在这里插入图片描述

2、基本操作

直方图、散点图、3D图、折线图、热力图、bar图。

2.1绘画直方图

#matplotlib使用
import matplotlib.pyplot as plt
from numpy.random import normal,rand
x = normal(size=200)
plt.hist(x,bins=30)
plt.show()

效果:
在这里插入图片描述
2.2散点图

#2、散点图
import matplotlib.pyplot as plt
from numpy.random import rand
a = rand(100)
b = rand(100)
plt.scatter(a,b)
plt.show()

效果:
在这里插入图片描述
其他散点图:

class Plot(object):
	def __init__(self, ref, pred):
		self.ref = ref
		self.pred = pred
    def plot(self):
        '''
        绘制预测类别分布图以及真实类别分布图
        输入:真实样本标签self.ref;实际结果标签self.pred
        输出:
        '''
#         font = {'family' : 'normal',
# #         'weight' : 'bold',
#         'size'   : 18}
#         matplotlib.rc('font', **font)
        #1.绘制真实标签分布
        fig1 = plt.figure('True_fig', figsize = (16,12))
        fig1.suptitle('True Label Distribution',fontsize = 20)
        ax1 = fig1.add_subplot(1,1,1)
        minorLocator = MultipleLocator(base = 413)
        ax1.scatter(x = np.arange(len(self.ref)), y = self.ref, c = 'red', marker = 'o',
                    linewidths = 0.01,
                    )#color = 'red', marker = 'o', markersize = 1,
        ticks1 = ax1.set_yticks(list(np.arange(22)))
        #也可以将其他值用作标签
        labels1 = ax1.set_yticklabels(['Normal','Fault 1', 'Fault 2','Fault 3','Fault 4','Fault 5','Fault 6','Fault 7','Fault 8', 'Fault 9', 
                                       'Fault 10', 'Fault 11', 'Fault 12', 'Fault 13', 'Fault 14', 'Fault 15', 'Fault 16', 'Fault 17', 
                                       'Fault 18', 'Fault 19', 'Fault 20', 'Fault 21'], 
                                      rotation=0, fontsize='small')
        # Set minor tick locations.
        ax1.yaxis.set_minor_locator(MultipleLocator(1))
        ax1.xaxis.set_minor_locator(minorLocator)
        yticks = FormatStrFormatter('')
        ax1.set_xlabel("sample NO.")
        ax1.set_ylabel("Label")
        # Set grid to use minor tick locations. 
        ax1.grid(which = 'minor')        
        extraticks = [9086]
        plt.xticks(list(plt.xticks()[0]) + extraticks)
        ax1.set_xlim(xmin = -100, xmax = 9200)
#         ax1.legend(loc = 'best')        
#         ax1.xaxis.set_tick_params(pad=2)

        for item in ([ax1.title, ax1.xaxis.label, ax1.yaxis.label]):
            item.set_fontsize(20)
        for item in (ax1.get_xticklabels()+ax1.get_yticklabels()):
            item.set_fontsize(14)   
        #+ )
        fig1.tight_layout(rect=[0, 0.03, 1, 0.95])

现在用的:

 #1.绘制真实标签分布
  fig1 = plt.figure('True_fig', figsize = (16,12))
  fig1.suptitle('True Label Distribution',fontsize = 20)
  ax1 = fig1.add_subplot(1,1,1)
  minorLocator = MultipleLocator(base = num)
  ax1.scatter(x = np.arange(len(self.ref)), y = self.ref, c = 'red', marker = 'o',
              linewidths = 0.01,
              )#color = 'red', marker = 'o', markersize = 1,
  ticks1 = ax1.set_yticks(list(np.arange(22)))
  #也可以将其他值用作标签
  labels1 = ax1.set_yticklabels(['Normal','Fault 1', 'Fault 2','Fault 3','Fault 4','Fault 5','Fault 6','Fault 7','Fault 8', 'Fault 9', 
                                 'Fault 10', 'Fault 11', 'Fault 12', 'Fault 13', 'Fault 14', 'Fault 15', 'Fault 16', 'Fault 17', 
                                 'Fault 18', 'Fault 19', 'Fault 20', 'Fault 21'], 
                                rotation=0, fontsize='small')
  # Set minor tick locations.
  ax1.yaxis.set_minor_locator(MultipleLocator(1))
  ax1.xaxis.set_minor_locator(minorLocator)
  yticks = FormatStrFormatter('')
  ax1.set_xlabel("sample NO.")
  ax1.set_ylabel("Label")
  # Set grid to use minor tick locations. 
  ax1.grid(which = 'minor')        
  extraticks = [length]
  plt.xticks(list(plt.xticks()[0]) + extraticks)
  ax1.set_xlim(xmin = xminValue, xmax = xmaxValue )
#         ax1.legend(loc = 'best')        
#         ax1.xaxis.set_tick_params(pad=2)

  for item in ([ax1.title, ax1.xaxis.label, ax1.yaxis.label]):
      item.set_fontsize(20)
  for item in (ax1.get_xticklabels()+ax1.get_yticklabels()):
      item.set_fontsize(14)   
  #+ )
  #tight_layout() only considers ticklabels, axis labels, and titles. 
  fig1.tight_layout(rect=[0, 0.03, 1, 0.95])
#         plt.savefig(picDir + "trueLabel{}.pdf".format(self.picName))
  if self.save:
      plt.savefig(picDir + "trueLabel{}.png".format(picName), dpi = (300))

2.3 3D图绘制

#3、3D图
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm)
plt.show()

效果:
在这里插入图片描述
scatter 的3D图:

# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 unused import

import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19680801)


def randrange(n, vmin, vmax):
    '''
    Helper function to make an array of random numbers having shape (n, )
    with each number distributed Uniform(vmin, vmax).
    '''
    return (vmax - vmin)*np.random.rand(n) + vmin

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

n = 100

# For each set of style and range settings, plot n random points in the box
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].
for m, zlow, zhigh in [('o', -50, -25), ('^', -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zlow, zhigh)
    ax.scatter(xs, ys, zs, marker=m)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

在这里插入图片描述

2.4 绘制折线图、散点图
以accuracy变化为例。

def plotAccuracy(trainAccList, testAccList):
    '''
    绘制精度图,原文:https://blog.csdn.net/tsq292978891/article/details/79862887 
    '''
    plt.figure(figsize=(25,16))
    plt.grid(linestyle = "--")      #设置背景网格线为虚线
    ax = plt.gca()
    #ax.spines['top'].set_visible(False)  #去掉上边框
    #ax.spines['right'].set_visible(False) #去掉右边框

#     xgroup_labels=['100%','80%','60%','40%','20%','0%'] #x轴刻度的标识
#     ygroup_labels=['0.0','0.1','0.2','0.3','0.4','0.5','0.6','0.7','0.8','0.9','1.0'] #y轴刻度的标识

#     plt.xticks(x,xgroup_labels[::-1],fontsize=18,fontweight='bold') #默认字体大小为10
#     plt.yticks(y,ygroup_labels,fontsize=18,fontweight='bold')
    # axis 0 and axis 1 Font
            
    # 先画折现图
    # [::-1]
    plt.plot(20*np.arange(len(trainAccList)), np.array(trainAccList), label="Train Accuracy",linewidth=4)
    plt.plot(20*np.arange(len(testAccList)), np.array(testAccList), label="Test Accuracy",linewidth=4)

    # 再画散点图
    plt.scatter(20*np.arange(len(trainAccList)), np.array(trainAccList),c = 'red',s=300,marker = '.')
    plt.scatter(20*np.arange(len(testAccList)), np.array(testAccList), c = 'green',s=300,marker = '.')

    plt.title("Accuracy",fontsize=20,fontweight='bold')    #默认字体大小为12
    plt.xlabel("Step",fontsize=20,fontweight='bold')
    plt.ylabel("Accuracy",fontsize=20,fontweight='bold')
#     plt.xlim(0.0,1.0)         #设置x轴的范围
    plt.ylim(0.0,1.0)

    plt.legend()          #显示各曲线的图例
    plt.legend(loc=3,numpoints=1)
    leg = plt.gca().get_legend()
    ltext = leg.get_texts()
    plt.setp(ltext,fontsize=22,fontweight='bold') #设置图例字体的大小和粗细
    
    for item in ([ax.title, ax.xaxis.label, ax.yaxis.label]):
        item.set_fontsize(20)
    for item in (ax.get_xticklabels()+ax.get_yticklabels()):
        item.set_fontsize(18)   
    plt.show()

在这里插入图片描述

添加竖线:

import matplotlib.pyplot as plt
import numpy as np 

def plotLoss(loss, step = 3, length = 25, height = 16):
    '''input: np.array
    output: two stage loss'''

    plt.figure(figsize=(length, height))
    plt.grid(linestyle = "--")      #设置背景网格线为虚线
    ax = plt.gca()
            
    # 先画折现图
    # [::-1]
    plt.plot(np.arange(len(loss)), np.array(loss), 
             label="loss",linewidth=4)

    # 再画散点图
    plt.scatter(np.arange(len(loss)), np.array(loss),c = 'red',s=300,marker = '.')

    plt.title("loss",fontsize=20,fontweight='bold')    #默认字体大小为12
    plt.xlabel("Step",fontsize=20,fontweight='bold')
    plt.ylabel("loss",fontsize=20,fontweight='bold')
    
    y_min = 0.0
    y_max = max(loss)*1.05
#     plt.xlim(0.0,1.0)         #设置x轴的范围
    plt.ylim(y_min, y_max)
    
    # 竖线分割两个阶段
    plt.vlines(step, y_min, y_max, colors = "c", linestyles = "dashed")
    
    plt.legend()          #显示各曲线的图例
    plt.legend(loc=3,numpoints=1)
    leg = plt.gca().get_legend()
    ltext = leg.get_texts()
    plt.setp(ltext,fontsize=22,fontweight='bold') #设置图例字体的大小和粗细
    
    for item in (ax.get_xticklabels()+ax.get_yticklabels()):
        item.set_fontsize(18)   
    plt.show()
    plt.close()
if __name__ == "__main__":
    loss = np.array([3, 2, 1 , 0.4, 0.2])
    plotLoss(loss, length = 10, height = 8)

效果:
在这里插入图片描述

import matplotlib.pyplot as plt
line = plt.plot([1,2,3], [1,2,3], 'go-', label='line 1', 
linewidth=2)
plt.legend(line)
plt.show()

在这里插入图片描述
marker 有:
在这里插入图片描述

2.5 数值用图表示imshow

def showArray(P, cmap = 'viridis'):
    '''
    show matrix with picture, and if the cmap is belongs to diverging colormaps,
    set midvalue as the center color.
    '''
    # The normal figure
    # Limits for the extent
    x_start = 0.0
    x_end = 1.0
    y_start = 0.0
    y_end = 1.0
    
    extent = [x_start, x_end, y_start, y_end]
    fig = plt.figure(figsize=(16, 12))
    ax = fig.add_subplot(111)
    im = ax.imshow(P, extent=extent, interpolation='None', cmap=cmap)
    fig.colorbar(im)
    
    # Add the text
    size = int(len(P))
    jump_x = (x_end - x_start) / (2.0 * size)
    jump_y = (y_end - y_start) / (2.0 * size)
    x_positions = np.linspace(start=x_start, stop=x_end, num=size, endpoint=False)
    y_positions = np.linspace(start=y_start, stop=y_end, num=size, endpoint=False)
    
    for y_index, y in enumerate(y_positions):
        for x_index, x in enumerate(x_positions):
            label = round(P[len(y_positions) - 1 - y_index, x_index], 2)
            text_x = x + jump_x
            text_y = y + jump_y
            ax.text(text_x, text_y, label, fontsize = 10, color='black', ha='center', va='center')
    plt.show()
    plt.close()
P = np.random.randint(low = 1,high = 10, size = (3,3))
showArray(P)

result:
在这里插入图片描述
如果我们需要设定中心值,

class MidpointNormalize(colors.Normalize):
	"""
	Normalise the colorbar so that diverging bars work there way either 
    side from a prescribed midpoint value)

	e.g. im=ax1.imshow(array, norm=MidpointNormalize(midpoint=0.,vmin=-100, vmax=100))
	"""
	def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
		self.midpoint = midpoint
		colors.Normalize.__init__(self, vmin, vmax, clip)

	def __call__(self, value, clip=None):
		# I'm ignoring masked values and all kinds of edge cases to make a
		# simple example...
		x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
		return np.ma.masked_array(np.interp(value, x, y), np.isnan(value))
    
def showArray(P, cmap = 'viridis', midvalue = 0):
    '''
    show matrix with picture, and if the cmap is belongs to diverging colormaps,
    set midvalue as the center color.
    '''
    # The normal figure
    # Limits for the extent
    x_start = 0.0
    x_end = 1.0
    y_start = 0.0
    y_end = 1.0
    
    extent = [x_start, x_end, y_start, y_end]
    fig = plt.figure(figsize=(16, 12))
    ax = fig.add_subplot(111)
    im = ax.imshow(P, extent=extent, interpolation='None', cmap=cmap,
                   norm=MidpointNormalize(midpoint= midvalue,vmin=np.min(P), vmax=np.max(P)))
    fig.colorbar(im)
    plt.show()
P = build_random_P(10, noise) - 0.1
showArray(P, cmap = 'seismic')

With center value setting:
在这里插入图片描述
Without center setting:
在这里插入图片描述
2.6 1D 绘图

import numpy as np
import matplotlib.pyplot as pp
val = 0. # this is the value where you want the data to appear on the y-axis.
ar = np.arange(10) # just as an example array
pp.plot(ar, np.zeros_like(ar) + val, 'x')
pp.show()

result:
在这里插入图片描述

2.7 bar 绘图

import matplotlib
import matplotlib.pyplot as plt
import numpy as np


labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]

x = np.arange(len(labels))  # the label locations
width = 0.35  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, label='Men')
rects2 = ax.bar(x + width/2, women_means, width, label='Women')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()


def autolabel(rects):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')


autolabel(rects1)
autolabel(rects2)

fig.tight_layout()

plt.show()

在这里插入图片描述

2.8双纵坐标绘图

def plot(tmpdf, tmpdf2,col_list,label_list,title="",xcol = "time",ylabel="",rotation = 0):
    fig = plt.figure(figsize=(10,5))
    ax1 = fig.add_subplot(111)
    ax1.plot(np.arange(len(tmpdf)), tmpdf[col_list[0]], 'g^-', markersize=6, label = label_list[0])
    ax1.set_ylabel(ylabel)
    ax1.legend(loc='best')

    ax2 = ax1.twinx()  # this is the important function
    ax2.plot(np.arange(len(tmpdf2)), tmpdf2[col_list[1]], 'yv-', markersize=6,
             label = label_list[1])
    
    ax2.legend(loc='best')
    ax2.set_ylabel(ylabel)
 
    if xcol:
        plt.xticks(np.arange(len(tmpdf[xcol])))
        ax1.set_xticklabels(tmpdf[xcol], rotation=rotation)
    if title:
        plt.title(title)
    if ylabel:
        plt.ylabel(ylabel)
    plt.grid()
    plt.show() 

3. 其他

极坐标绘图:

import math
import numpy as np
sin = np.sin 
pi = np.pi 
import matplotlib.pyplot as plt

theta=np.arange(0,2*np.pi,0.02)
ax1 = plt.subplot(121, projection='polar')
ax1.plot(theta,2*np.abs(sin(2*theta)) + np.abs(sin(4*theta)),'--',lw=2)
plt.show()

在这里插入图片描述
3.2 动图

# -*- coding: utf-8 -*-
"""
Created on Tue Jun 18 20:51:48 2019

@author: win10
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

fig, ax = plt.subplots()

x = np.arange(0, 2 * np.pi, 0.01)
line0 = ax.plot(x, np.cos(x))
line, = ax.plot(x, np.sin(x))

def init():
    line.set_ydata(np.sin(x))
    return line,

def animate(i):
    line.set_ydata(np.sin(x + i / 10.0))
    return line,

animation = animation.FuncAnimation(fig=fig, func=animate, frames=100,
                                    init_func=init, interval=20, blit=False)

animation.save('resetvalue.gif', writer='imagemagick')
plt.show()

在这里插入图片描述
(缺陷:只重复展示过程一次)
在这里插入图片描述
此外,需要额外下载 imagemagick

4.Color

Alias Color
‘b’ blue
‘g’ green
‘r’ red
‘c’ cyan
‘m’ magenta
‘y’ yellow
‘k’ black
‘w’ white

5.其他绘图包

pyechart


参考:

  1. matplotlib;
  2. Guide to matplotlib;
  3. Accuracy 绘制;
  4. imshow stackoverflow;
  5. cmap type select;
  6. Centre a diverging colorbar at a defined value with matplotlib
  7. 1 维绘图
  8. 动图生成 animation
  9. animation 解释;
  10. animation 官网 ;
  11. zhihu matplotlib 动图
  12. Marker;
  13. Bar绘图
  14. python 双Y轴;
  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rosefunR

你的赞赏是我创作的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值