Matplotlib

Matplotlib:线类型

Matplotlib:legend 图例

生成透明背景

plt.savefig('./变化.png'.format(last_data),  bbox_inches='tight',transparent=True)
# bbox_inches='tight' 图片边界空白紧致
# transparent=True  背景透明

Matplotlib输出中文显示问题

from pylab import mpl

mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题

Matplotlib中指定图片大小和像素

plt.savefig(‘plot123_2.png’, dpi=200)#指定分辨率


#figsize(12.5, 4) # 设置 figsize
plt.rcParams['savefig.dpi'] = 300 #图片像素
plt.rcParams['figure.dpi'] = 300 #分辨率
# 默认的像素:[6.0,4.0],分辨率为100,图片尺寸为 600&400
# 指定dpi=200,图片尺寸为 1200*800
# 指定dpi=300,图片尺寸为 1800*1200
# 设置figsize可以在不改变分辨率情况下改变比例

matplotlib调整子图间距,调整整体空白的方法

matplotlib.pyplot.subplots_adjust(left=None,
 bottom=None, 
 right=None, 
 top=None, 
 wspace=None, 
 hspace=None)

left = 0.125  # the left side of the subplots 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 space between subplots,
              # expressed as a fraction of the average axis width
hspace = 0.2  # the amount of height reserved for space between subplots,
              # expressed as a fraction of the average axis height
fig.tight_layout()#调整整体空白
plt.subplots_adjust(wspace =0, hspace =0)#调整子图间距

设置axes脊柱(坐标系)

ax = plt.gca() # 获取当前的axes
属性列表在这里插入图片描述
(1)去掉脊柱(坐标系)

ax.spines[‘top’].set_visible(False) #去掉上边框

ax.spines[‘bottom’].set_visible(False) #去掉下边框

ax.spines[‘left’].set_visible(False) #去掉左边框

ax.spines[‘right’].set_visible(False) #去掉右边框

(2)移动脊柱

ax.spines[‘right’].set_color(‘none’)
ax.spines[‘top’].set_color(‘none’)
ax.xaxis.set_ticks_position(‘bottom’)  ##刻度的显示位置(轴的下面/上面)
ax.spines[‘bottom’].set_position((‘data’,0))
ax.yaxis.set_ticks_position(‘left’)
ax.spines[‘left’].set_position((‘data’,0))
plt.tick_params(axis="x",labelrotation=-60)

ax=plt.gca()
ax.spines['top'].set_visible(False) #去掉上边框
ax.spines['right'].set_visible(False) #去掉上边框
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0.5))

(3)设置边框线颜色
ax = plt.gca() # 获取当前的axes

ax.spines['right'].set_color('blue')
ax.spines['top'].set_color('none')

(4)设置边框线宽

ax1.spines['left'].set_linewidth(5)

(5)设置边框线型

ax.spines['left'].set_linestyle('--')

(6).设置反方向x轴(y轴同理)

ax.invert_xaxis()  # x轴反向
plt.tick_params(axis="x",labelrotation=-60)
ax=plt.gca()
ax.spines['top'].set_visible(False) #去掉上边框
ax.spines['right'].set_visible(False) #去掉上边框
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0.5))
ax.invert_xaxis()  # x轴反向

示例:

# 导入模块
import matplotlib.pyplot as plt
import numpy as np

# 数据
x = np.linspace(-10, 10, 100)
y = x**2

# 绘图
plt.plot(x, y)

ax = plt.gca()
# ===设置脊(边框)===
# 1.隐藏上与右的边框
ax.spines['top'].set_visible(False)
ax.spines['right'].set_color(None)

# 2.设置颜色
ax.spines['left'].set_color('b')
ax.spines['bottom'].set_color('r')

# 3.设置线宽
ax.spines['left'].set_linewidth(5)
ax.spines['bottom'].set_linewidth(3)

# 4.设置线形
ax.spines['left'].set_linestyle('--')
ax.spines['left'].set_linestyle('-.')

# 5.设置交点位置(0, 35)
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 35))

# 6.设置数据显示的位置
#ax.xaxis.set_ticks_position('bottom')
#ax.yaxis.set_ticks_position('right')


# 7.设置反方向(y轴同理)
ax.invert_xaxis()  # x轴反向

# 展示
plt.show()

在这里插入图片描述
将坐标轴移到中间,即笛卡尔坐标轴。路径:将图形上,右边隐藏,将下,左边移动到中间,需要用到gca函数获取Axes对象,接着通过这个对象指定每条边的位置,使用set_color设置成none。实现代码如下:

x = np.arange(-2*np.pi,2*np.pi,0.01)#定义横轴范围
y = np.sin(3*x)/x#函数
y2 = np.sin(2*x)/x
y3 = np.sin(x)/x
plt.plot(x,y)#绘制,matplotlib默认展示不同的颜色
plt.plot(x,y2,'--')
plt.plot(x,y3)
plt.xticks([-2*np.pi,-np.pi,0,np.pi,2*np.pi],[r'$-2\pi$',r'$\pi$','$0$','$\pi$','$2\pi$'])#显示横坐标刻度值,不加第二个参数,将显示的是数值而不是字母
plt.yticks([-1,0,1,2,3],[r'$-1$','$0$','$+1$','$+2$','$+3$'])
plt.legend(['y','y2','y3'])
plt.title('M10')
ax = plt.gca()#使用gca函数获取axes对象
ax.spines['right'].set_color('none')#右侧边隐藏
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')#将底边设为横坐标
ax.spines['bottom'].set_position(('data',0))#将坐标置于坐标0处
ax.yaxis.set_ticks_position('left')#左边设置为纵坐标
ax.spines['left'].set_position(('data',0))
plt.show()


Matplotlib:tick_params语法

Axes.tick_params(axis=‘both’, **kwargs)
  • axis : {‘x’, ‘y’, ‘both’} Axis on which to operate; default is ‘both’.
    reset : bool If True, set all parameters to defaults before processing other keyword arguments. Default is False.
  • which : {‘major’, ‘minor’, ‘both’} Default is ‘major’; apply arguments to which ticks.
  • direction : {‘in’, ‘out’, ‘inout’} Puts ticks inside the axes, outside the axes, or both.
  • length : float Tick length in points.
  • width : float Tick width in points.
  • color : color Tick color; accepts any mpl color spec.
  • pad : float Distance in points between tick and label.
  • labelsize : float or str Tick label font size in points or as a string (e.g., ‘large’).
    参数labelsize用于设置刻度线标签的字体大小
  • labelcolor : color Tick label color; mpl color spec.
  • colors: color Changes the tick color and the label color to the same value: mpl color spec.
  • zorder: float Tick and label zorder.
  • bottom, top, left, right : bool or {‘on’, ‘off’} controls whether to draw the respective ticks.
    参数bottom, top, left, right的值为布尔值,分别代表设置绘图区四个边框线上的的刻度线是否显示
  • labelbottom, labeltop, labelleft, labelright: bool or {‘on’, ‘off’} controls whether to draw the respective tick labels.
    参数labelbottom, labeltop, labelleft, labelright的值为布尔值,分别代表设置绘图区四个边框线上的刻度线标签是否显示
  • labelrotation : float Tick label rotation

Matplotlib:背景设置

函数:


figure(num=None, 
		figsize=None, 
		dpi=None, 
		facecolor=None, 
		edgecolor=None, 
		frameon=True, 
		FigureClass=Figure, 
		clear=False, 
		**kwargs
	)

参数:

  • num : integer or string, optional, default: none,num:如果此参数没有提供,则一个新的figure对象将被创建,同时增加figure的计数数值,此数值被保存在figure对象的一个数字属性当中。如果有此参数,且存在对应id的figure对象,则激活对于id的figure对象。如果对应id的figur对象不存在,则创建它并返回它。如果num的值是字符串,则将窗口标题设置为此字符串。
  • figsize : tuple of integers, optional, default: None
    width, height in inches. If not provided, defaults to rc figure.figsize
    figsize:以英寸为单位的宽高,缺省值为 rc figure.figsize (1英寸等于2.54厘米)
  • dpi : integer, optional, default: None dpi:图形分辨率,缺省值为rc figure.dpi
  • facecolor :the background color. If not provided, defaults to rc figure.facecolo
  • edgecolor :the border color. If not provided, defaults to rc figure.edgecolor
    edgecolor:边框颜色
  • clear: bool, optional, default: False
    If True and the figure already exists, then it is cleared
    clear:重建figure实例

设置栅格

matplotlin.pyplot.grid(b, 
						which, 
						axis, 
						color, 
						linestyle, 
						linewidth, 
						**kwargs
					)
  • b: 布尔值。就是是否显示网格线的意思。官网说如果b设置为None, 且kwargs长度为0,则切换网格状态。但是没弄明白什 么意思。如果b设置为None,但是又给了其它参数,则默认None值失效。

  • which : 取值为’major’, ‘minor’, ‘both’。 默认为’major’。看别人说是显示的,我的是Windows7下,用Sublime跑的,minor 只是一个白画板,没有网格,major和both也没看出什么效果,不知道为什么。

  • axis: 取值为‘both’, ‘x’,‘y’。就是想绘制哪个方向的网格线。不过我在输入参数的时候发现如果输入x或y的时候, 输入的是哪条轴,则会隐藏哪条轴

  • color : 就是设置网格线的颜色。或者直接用c来代替color也可以。

  • linestyle :也可以用ls来代替linestyle, 设置网格线的风格,是连续实线,虚线或者其它不同的线条。 | ‘-’ | ‘–’ | ‘-.’ | ‘:’ | ‘None’ | ’ ’ | ‘’]

  • linewidth : 设置网格线的宽度

  • alpha:设置透明度
    在这里插入图片描述

主、副刻度密度的设置

需要导入:from matplotlib.ticker import MultipleLocator, FormatStrFormatter 模块
主刻度:(y轴同理)

倍数:ax.xaxis.set_major_locator(MultipleLocator(倍数))
文本格式:ax.xaxis.set_major_formatter(FormatStrFormatter(’%占位数.小数点数f’))
副刻度:(将"major"改为"minor"即可)
倍数:ax.xaxis.set_minor_locator(MultipleLocator(倍数))
文本格式:ax.xaxis.set_minor_formatter(FormatStrFormatter(’%占位数.小数点数f’))

# 导入模块
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
import numpy as np

# 数据
x = np.linspace(-30, 30, 100)
y = x**2

# 绘图
plt.plot(x, y)

ax = plt.gca()
# 设置轴的主刻度
# x轴
ax.xaxis.set_major_locator(MultipleLocator(20))  # 设置20倍数
ax.xaxis.set_major_formatter(FormatStrFormatter('%5.1f'))  # 设置文本格式

# y轴
ax.yaxis.set_major_locator(MultipleLocator(100))  # 设置100倍数
ax.yaxis.set_major_formatter(FormatStrFormatter('%1.2f'))  # 设置文本格式

# 设置轴的副刻度
# x轴
ax.xaxis.set_minor_locator(MultipleLocator(5))  # 设置10倍数
# ax.xaxis.set_minor_formatter(FormatStrFormatter('%2.1f'))  # 设置文本格式

# y轴
ax.yaxis.set_minor_locator(MultipleLocator(50))  # 设置50倍数
# ax.yaxis.set_minor_formatter(FormatStrFormatter('%1.0f'))  # 设置文本格式

# 设置网格
ax.xaxis.grid(True, which='major')  # x坐标轴的网格使用主刻度
ax.yaxis.grid(True, which='minor')  # y坐标轴的网格使用次刻度

# 展示
plt.show()

设置水平参考线和垂直参考线

axhline() / axvline()

ax ~ axis h ~ horizontal,水平的 v ~ vertical,垂直的

组合起来看,这两个函数分别用于设置水平参考线和垂直参考线。
import matplotlib.pyplot as plt
import numpy as np

# 生成数据
x = np.linspace(0, 10, 100)
y = np.sin(x)

# 使用scatter绘图
plt.plot(x, y, ls='-.', lw=2, c='c', label='sin(x)')
plt.legend()

# 这里的参数跟上面函数的参数类似,
plt.axhline(y=0, c='r', ls='--', lw=2)
plt.axvline(x=5, c='g', ls='-.', lw=2)

plt.show()

在这里插入图片描述

设置平行于x轴/y轴的参考区域

axhspan() / axvspan()

ax ~ axis h ~ horizontal,水平的 
v ~ vertical,垂直的 span ~ 跨度,区间,范围
这两个函数分别用于设置平行于x轴/y轴的参考区域。
import matplotlib.pyplot as plt
import numpy as np

# 生成数据
x = np.linspace(0, 10, 100)
y = np.sin(x)

# 使用scatter绘图
plt.plot(x, y, ls='-.', lw=2, c='c', label='sin(x)')
plt.legend()

# xmin/xmax/ymin/ymax用于设置区间范围
# facecolor用于设置区域颜色
# alpha用于设置透明度
plt.axhspan(ymin=-0.25, ymax=0.25, facecolor='purple', alpha=0.3)
plt.axvspan(xmin=4, xmax=6, facecolor='g', alpha=0.3)

plt.show()

在这里插入图片描述

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(20))
ax.axvspan(8, 14, ymin=0.1, ymax=0.9, alpha=0.5, color='red')

plt.show()

在这里插入图片描述

日期格式的标签自动旋转

以x轴的数为日期,再以plt.gcf().autofmt_xdate()来旋转显示日期数据。

# 导入模块
import matplotlib.pyplot as plt
import numpy as np

# 数据
N = 4
y = np.random.randint(-20, 20, (1, N)).flatten()
x = ["2019-3-13", "2019-3-14", "2019-3-15", "2019-3-16"]
# 绘图
plt.plot(x, y)
# 旋转日期显示
plt.gcf().autofmt_xdate()
# 展示
plt.show()

x轴标签旋转(https://blog.csdn.net/songrenqing/article/details/78927283)

调整x轴标签,从垂直变成水平或者任何你想要的角度,只需要改变rotation的数值。

for tick in ax1.get_xticklabels():

    tick.set_rotation(360)

或者

import pylab as pl

pl.xticks(rotation=360)

坐标轴标签设置

Axes.set_yticklabels(self, labels, 
					fontdict=None, 
					minor=False, 
					**kwargs)

Axes.set_xticklabels(self, labels,
					 fontdict=None,
					  minor=False, **kwargs)
Parameters:	
	labels : List[str]
				List of string labels.
	fontdict : dict, optional

示例:
ax.set_xticklabels(
    labels = types[1:],
    fontdict={
        'rotation': 'vertical',
        'fontsize': 18
    })

文本标注,数据点注释

在这里插入图片描述
带箭头的参数:

	s : "string"
	
	xy: 箭头的坐标
	
	xytext: 文字的坐标
	
	arrowprops: 箭头的属性,字典类型
	
	arrowprops=dict(facecolor="red", shrink=0.1, width=2)
	
	facecolor:箭头颜色
	
	shrink:箭头的长度(两坐标距离的比例,0~1)
	
	width:箭头的宽度

在这里插入图片描述

import matplotlib.pyplot as plt

y = [3, 1, 4, 5, 2]
plt.plot(y)

# x , y 轴标签
plt.ylabel("纵轴的值", fontproperties="SimHei", fontsize=20)
plt.xlabel("横轴的值", fontproperties="SimHei", fontsize=20, color="green")

# 整体的标签
plt.title(r"整体的标签 $x^{2y +3}$", fontproperties="SimHei", fontsize=30)

# 显示网格
plt.grid(True)

# 再坐标为(1,3)处输出文字
plt.text(1, 3, r"$\mu=100$")

# 有箭头的文字
plt.annotate(r"$\sum_1^nx$", xy=(3, 3), xytext=(3, 4.5),
             arrowprops=dict(facecolor="red", shrink=0.1, width=2))

# 设置坐标轴 x(0, 4) y(0, 6)
plt.axis([0, 4, 0, 6])
plt.show()

在这里插入图片描述
#添加注释 annotate

# 添加注释 annotate
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
             textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))

在这里插入图片描述
添加注释text

	matplotlib.pyplot.text(x, y, s,
	 fontdict=None, 
	 withdash=False, 
	 **kwargs
	 )
参数:
# 第一个参数是x轴坐标
# 第二个参数是y轴坐标
# 第三个参数是要显式的内容
# alpha 设置字体的透明度
# family 设置字体
# size 设置字体的大小
# style 设置字体的风格
# wight 字体的粗细
# bbox 给字体添加框,alpha 设置框体的透明度, facecolor 设置框体的颜色

示例:

plt.text(-3, 20, "function: y = x * x", size = 15, alpha = 0.2)
plt.text(-3, 40, "function: y = x * x", size = 15,\
         family = "fantasy", color = "r", style = "italic", weight = "light",\
         bbox = dict(facecolor = "r", alpha = 0.2))

plt.show()

在这里插入图片描述

# 添加注释 text  
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
         fontdict={'size': 16, 'color': 'r'})

添加plt.figtext()

'''
第一种方式 text()
 text(x,y,s,fontdict=None, withdash=False)
    参数说明:(1)x,y 坐标位置
             (2) 显示的文本
'''
x = np.arange(0,2*np.pi,0.01)
plt.plot(np.sin(x))
'''x,y 代表着坐标系中数值'''
plt.text(20,0,'sin(0) = 0')
'''
第二种方式  figtext()
    使用figtext时候,x,y代表相对值,图片的宽度
    
'''
x2 = np.arange(0,2*np.pi,0.01)
plt.plot(np.cos(x2))
''''''
plt.figtext(0.5,0.5,'cos(0)=0')
plt.show()

添加数据标签

# -*- coding: utf-8 -*-
import time
import matplotlib.pyplot as plt

def showResult(xList, yList, title, xLabel, yLabel):
    plt.plot(xList, yList, 'g*-')
    plt.title(title)
    plt.xlabel(xLabel)
    plt.ylabel(yLabel)
    for x, y in zip(xList, yList):
        plt.text(x, y+0.3, str(y), ha='center', va='bottom', fontsize=10.5)
    plt.savefig('fig'+str(int(time.time()))+'.jpg')
    plt.show()

x_arr = [1, 2, 3, 4, 5, 6]
y_arr = [1, 4, 9, 16, 25, 36]
showResult(x_arr, y_arr, 'title', 'x', 'y')


其中

for x, y in zip(xList, yList):
	plt.text(x, y+0.3, '%.0f'%y, ha='center', va='bottom', fontsize=10.5)

逐个获取需要标注的点的横纵坐标 x与 y,然后在位置 (x, y+0.3) 处以 10.5 的字体显示出 y 的值,‘center’ 和 ‘bottom’ 分别指水平和垂直方向上的对齐方式。
在这里插入图片描述

设置坐标轴范围

在使用matplotlib模块时画坐标图时,往往需要对坐标轴设置很多参数,这些参数包括横纵坐标轴范围、坐标轴刻度大小、坐标轴名称等

  • xlim():设置x坐标轴范围
  • ylim():设置y坐标轴范围
  • xlabel():设置x坐标轴名称
  • ylabel():设置y坐标轴名称
  • xticks():设置x轴刻度
  • yticks():设置y轴刻度
y的和x的一样
xticks(ticks, [labels], **kwargs)  # Set locations and labels
参数:
		ticks : array_like
		A list of positions at which ticks should be placed. You can pass an empty list to disable xticks.
		
		labels : array_like, optional
		A list of explicit labels to place at the given locs.
		
		**kwargs
		Text properties can be used to control the appearance of the labels.

限制x轴和y轴的范围

plt.xlim() 和 plt.ylim()
调用方式说明
xlim()返回 xmin, xmax
xlim(xmin, xmax) 或 xlim((xmin, xmax))设置 x 轴的最大、最小值
xlim(xmax = n) 和 xlim(xmin = n)设置 x 轴的最大或最小值
#创建数据
x = np.linspace(-5, 5, 100)
y1 = np.sin(x)
y2 = np.cos(x)

#创建figure窗口,figsize设置窗口的大小
plt.figure(num=3, figsize=(8, 5))
#画曲线1
plt.plot(x, y1)
#画曲线2
plt.plot(x, y2, color='blue', linewidth=5.0, linestyle='--')
#设置坐标轴范围
plt.xlim((-5, 5))
plt.ylim((-2, 2))
#设置坐标轴名称
plt.xlabel('xxxxxxxxxxx')
plt.ylabel('yyyyyyyyyyy')
#设置坐标轴刻度
my_x_ticks = np.arange(-5, 5, 0.5)
#对比范围和名称的区别
#my_x_ticks = np.arange(-5, 2, 0.5)
my_y_ticks = np.arange(-2, 2, 0.3)
plt.xticks(my_x_ticks)
plt.yticks(my_y_ticks)

#显示出所有设置
plt.show()


#自定定义刻度线标签

plt.yticks([-2, -1.8, -1, 1.22, 3],
	['$really\ bad$', '$bad$', '$normal$', '$good$', '$really\ good$'])

坐标轴显示范围设置set_bounds

ax2.plot(x, y)

# Only draw spine between the y-ticks
ax2.spines['left'].set_bounds(-1, 1)

在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt


x = np.linspace(0, 2*np.pi, 50)
y = np.sin(x)
y2 = y + 0.1 * np.random.normal(size=x.shape)

fig, ax = plt.subplots()
ax.plot(x, y, 'k--')
ax.plot(x, y2, 'ro')

# set ticks and tick labels
ax.set_xlim((0, 2*np.pi))
ax.set_xticks([0, np.pi, 2*np.pi])
ax.set_xticklabels(['0', '$\pi$', '2$\pi$'])
ax.set_ylim((-1.5, 1.5))
ax.set_yticks([-1, 0, 1])

# Only draw spine between the y-ticks
ax.spines['left'].set_bounds(-1, 1)
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')

plt.show()

在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值