[python]matplotlib

整体图示

.ipynb 转换md时候图片不能通知携带,所有图片失效,不过直接运行代码可以执行

image

figure figure,axes与axis

image

import matplotlib.pyplot as plt
fig=plt.figure()
fig2=plt.subplots()
fig3,axs=plt.subplots(2,2)
plt.show()

[python]matplotlib_第1张图片

[python]matplotlib_第2张图片

Axes:一个图形上的数据点

  • 数据限制可以通过 axes.Axes.set_xlim()和 axes.Axes.set_ylim() 方法
  • 每个Axes都有一个标题(通过 set_title() 设置)、一个 x 标签(通过 set_xlabel() 设置)和一个通过 set_ylabel() 设置的 y 标签

Axis

  • number-line的对象,即我们日常说的坐标轴
  • 负责设置图形限制并生成刻度(轴上的标记)和刻度标签(标记刻度的字符串)
  • 刻度的位置由 Locator 对象确定,刻度标签字符串由 Formatter 格式化

Artist

  • 图上看到的所有东西都是Artist(甚至是 Figure、Axes和Axis对象
  • 包括 Text 对象、Line2D 对象、collections对象、Patch 对象
  • 渲染图形时,所有的Artist会被绘制到画布上。其中大多数Artist会被绑在轴上,这些Artist不能被多个轴共享,也不能从一个轴移动到另一个轴
fig,ax=plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
[]

[python]matplotlib_第3张图片

Axes 绘图方法,matplotlib.pyplot 模块中有一个相应的函数可以在“当前”轴上执行该绘图,如果它们尚不存在,则会创建该轴(及其父图形

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

[python]matplotlib_第4张图片

一个完整的绘画

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

plt.show()

[python]matplotlib_第5张图片

#上述代码相当于

fig,ax=plt.subplots()
ax.plot([1,2,3,4],[1,4,2,3])
plt.show()

[python]matplotlib_第6张图片

绘图函数的输入类型

  • 所有绘图函数都需要 numpy.array 或 numpy.ma.masked_array 作为输入
import pandas as pd
import numpy as np

a=pd.DataFrame(np.random.rand(4,5),columns=list('abcde'))
a_asarray=a.values
print(a)
print(a_asarray)

          a         b         c         d         e
0  0.942851  0.469160  0.163871  0.383466  0.482122
1  0.153815  0.297769  0.402677  0.449713  0.501791
2  0.084304  0.471720  0.446233  0.112047  0.172477
3  0.648961  0.762354  0.651969  0.436571  0.151777
[[0.94285104 0.46915987 0.16387077 0.38346593 0.4821217 ]
 [0.15381521 0.2977688  0.4026774  0.44971345 0.50179147]
 [0.08430377 0.47171985 0.44623296 0.11204723 0.172477  ]
 [0.64896052 0.76235361 0.65196889 0.43657115 0.15177734]]
b=np.matrix([[1,2],[3,4]])
b_asarray=np.asanyarray(b)
print(b)
print(b_asarray)
[[1 2]
 [3 4]]
[[1 2]
 [3 4]]

object-oriented接口和pyplot接口

  • 两种使用 Matplotlib 的方法
    • 创建图形和轴,并在它们上调用方法(“面向对象 (OO) ”)
    • 依靠 pyplot 自动创建和管理图形和坐标轴,并使用 pyplot 函数进行绘图
## oo方法
x=np.linspace(0,2,100)
fig,ax=plt.subplots()

ax.plot(x,x,label='linear')
ax.plot(x,x**2,label='quadratic')
ax.plot(x,x**3,label='cubic')
ax.set_xlabel('x_label')
ax.set_ylabel('y_label')
ax.set_title("Simple label")
ax.legend() ## 添加图例
plt.show()

[python]matplotlib_第7张图片

重复利用

def my_plotter(ax,data1,data2,param_dict):
    out=ax.plot(data1,data2,**param_dict)
    return out
data1,data2,data3,data4=np.random.randn(4,100)
fig,ax=plt.subplots(1,1)
my_plotter(ax,data1,data2,{'marker':'x'})
plt.show()

[python]matplotlib_第8张图片

fig,(ax1,ax2)=plt.subplots(1,2)
data1, data2, data3, data4 = np.random.randn(4, 100)
my_plotter(ax1,data1,data2,{'marker':'x'})
my_plotter(ax2,data3,data4,{'marker':'o'})
plt.show()

 

[python]matplotlib_第9张图片

简化

线段简化

  • path.simplify 参数是一个布尔值,指示线段是否被简化

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

y=np.random.rand(100000)
y[50000:]*=2
y[np.linspace(1,np.log10(5000),400).astype(int)]=-1
mpl.rcParams['path.simplify']=True
mpl.rcParams['path.simplify_threshold']=0.0

plt.plot(y)
plt.show()

[python]matplotlib_第10张图片

Matplotlib 默认为 1/9 的保守简化阈值

标记简化

  • 标记简化仅适用于 Line2D 对象(通过 markevery 属性
x=[1,2,3,4]
y=[1,3,3,2]
plt.plot(x, y, markevery=10)
[]

[python]matplotlib_第11张图片

pyplot教程

  • matplotlib.pyplot 是使 matplotlib 像 MATLAB 一样工作的命令样式函数的集合
  • 每个 pyplot 函数都会对图形进行一些更改,例如,创建图形、在图形中创建绘图区域、在绘图区域中绘制一些线、用标签装饰绘图等。

使用 pyplot 生成可视化非常快

import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()

[python]matplotlib_第12张图片

plot() 命令提供单个列表或数组,matplotlib 会假定它是一个 y 值序列,并自动为你生成 x 值.
默认的 x 向量的长度与 y 相同,但从 0 开始,因此 x 数据为 [0, 1, 2, 3]

import matplotlib.pyplot as plt
plt.plot([1,2,3,4],[1,4,9,16])
plt.show()

[python]matplotlib_第13张图片

添加颜色

import matplotlib.pyplot as plt
plt.plot([1,2,3,4],[1,4,9,16],'ro')
plt.axis([0,6,0,20])
plt.show()

[python]matplotlib_第14张图片

axis() 命令采用 [xmin, xmax, ymin, ymax] 列表来指定x、y轴的范围

使用数组在一个命令中绘制具有不同样式的多条线

import matplotlib.pyplot as plt
import numpy as np

t=np.arange(0.,5.,0.2)
plt.plot(t,t,'r--',t,t**2,'bs',t,t**3,'g^')
plt.show()

[python]matplotlib_第15张图片

使用关键字字符串绘图

数据格式允许你使用字符串访问特定变量。例如numpy.recarray 或 pandas.DataFrame
atplotlib 允许你为这样的对象提供 data 关键字参数,并使用与这些变量对应的字符串生成图

data={'a':np.arange(50),
      'c':np.random.randint(0,50,50),
      'd':np.random.randn(50),
      }
data['b']=data['a']+10*np.random.randn(50)
data['d']=np.abs(data['d'])*100

plt.scatter('a','b',c='c',s='d',data=data)
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()

[python]matplotlib_第16张图片

import matplotlib.pyplot as plt

names = ['group_a', 'group_b', 'group_c']
values = [1, 10, 100]


plt.figure(figsize=(9, 3))
## (131) 表示将绘图区域划分为一个 1x3 的网格(1 行 3 列),并选择当前要绘制的子图为第 1 个子图
plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()

[python]matplotlib_第17张图片

线属性

线宽、虚线样式、反走样等

使用关键字参数


x=[1, 2, 3, 4]
plt.plot(x,linewidth=3.0) #设置宽限

plt.ylabel('some numbers')
plt.show()

[python]matplotlib_第18张图片

使用 Line2D 的setter 方法

import matplotlib.pyplot as plt
 
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
 
line, = plt.plot(x, y, '-')
line.set_antialiased(False) # 关闭antialiasing
 
print(line) # >>> Line2D(_child0)
plt.show()
Line2D(_child0)

[python]matplotlib_第19张图片

要获取可设置属性的列表,可以使用一行或多行作为参数调用 setp() 函数

import matplotlib.pyplot as plt
 
lines = plt.plot([1, 2, 3])
print(plt.setp(lines))
  agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image
  alpha: scalar or None
  animated: bool
  antialiased or aa: bool
  clip_box: `~matplotlib.transforms.BboxBase` or None
  clip_on: bool
  clip_path: Patch or (Path, Transform) or None
  color or c: color
  dash_capstyle: `.CapStyle` or {'butt', 'projecting', 'round'}
  dash_joinstyle: `.JoinStyle` or {'miter', 'round', 'bevel'}
  dashes: sequence of floats (on/off ink in points) or (None, None)
  data: (2, N) array or two 1D arrays
  drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default'
  figure: `~matplotlib.figure.Figure`
  fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'}
  gapcolor: color or None
  gid: str
  in_layout: bool
  label: object
  linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
  linewidth or lw: float
  marker: marker style string, `~.path.Path` or `~.markers.MarkerStyle`
  markeredgecolor or mec: color
  markeredgewidth or mew: float
  markerfacecolor or mfc: color
  markerfacecoloralt or mfcalt: color
  markersize or ms: float
  markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool]
  mouseover: bool
  path_effects: list of `.AbstractPathEffect`
  picker: float or callable[[Artist, Event], tuple[bool, dict]]
  pickradius: float
  rasterized: bool
  sketch_params: (scale: float, length: float, randomness: float)
  snap: bool or None
  solid_capstyle: `.CapStyle` or {'butt', 'projecting', 'round'}
  solid_joinstyle: `.JoinStyle` or {'miter', 'round', 'bevel'}
  transform: `~matplotlib.transforms.Transform`
  url: str
  visible: bool
  xdata: 1D array
  ydata: 1D array
  zorder: float
None

[python]matplotlib_第20张图片

使用 setp() 命令


x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
 
lines = plt.plot(x, y)
plt.step(x,y,color='r',linewidth=2.0)
plt.show()

[python]matplotlib_第21张图片

多个图形和轴

import matplotlib.pyplot as plt
import numpy as np
 
def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)
 
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
 
plt.figure()
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
 
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

[python]matplotlib_第22张图片

subplot() 命令指定 numrows、numcols、plot_number。

import matplotlib.pyplot as plt
plt.figure(1)                # 第一个图形
plt.subplot(211)             # 第一个图形中的第1个子图
plt.plot([1, 2, 3])
plt.subplot(212)             # 第一个图形中的第2个子图
plt.plot([4, 5, 6])
 
plt.figure(2)                # 第二个图形
plt.plot([4, 5, 6])          # 创建默认子图,默认subplot(111)
 
plt.figure(1)                # 当前图形为figure 1; 由于subplot(212) 在211后面定义,所以当前子图为subplot(212)
plt.subplot(211)             # 定义当前子图为subplot(211) 
plt.title('Easy as 1, 2, 3') # 给211子图定义标题
 
plt.show()

[python]matplotlib_第23张图片

[python]matplotlib_第24张图片

文本处理

import matplotlib.pyplot as plt
import numpy as np
 
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
 
# 柱状图
n, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)
 
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

[python]matplotlib_第25张图片

plt.xlabel('my data', fontsize=14, color='red')
Text(0.5, 0, 'my data')

[python]matplotlib_第26张图片

注释文本

text() 命令的使用可以将文本放置在轴上的任意位置
文本的一个常见用途是对绘图的某些特征进行注释,并且 annotate() 方法提供了帮助功能使注释变得容易
在注释中,需要考虑两点:参数 xy 表示的被注释位置和文本 xytext 的位置,这两个参数都是 (x, y) 元组

import matplotlib.pyplot as plt
import numpy as np
 
ax = plt.subplot(111)
 
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)
 
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
             arrowprops=dict(facecolor='black', shrink=0.05),
             )
'''
local max:注释的内容
xy:箭头头的坐标
 xytext:注释内容的起始位置
arrowprops:设置箭头的一些属性,颜色、宽度等
'''
plt.ylim(-2, 2)
plt.show()

[python]matplotlib_第27张图片

对数轴

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(19680801)

y=np.random.normal(loc=0.5,scale=4,size=1000)
y=y[(y>0)&(y<1)]
y.sort()
x=np.arange(len(y))

plt.figure()

#linear
plt.subplot(121)
plt.plot(x,y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)

# log
plt.subplot(122)
plt.plot(x,y)
plt.yscale('log')
plt.title('log')
plt.grid(True)

[python]matplotlib_第28张图片

图片处理

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread('data.png')
print(img)
[[0.40784314 0.40784314 0.40784314 ... 0.42745098 0.42745098 0.42745098]
 [0.4117647  0.4117647  0.4117647  ... 0.42745098 0.42745098 0.42745098]
 [0.41960785 0.41568628 0.41568628 ... 0.43137255 0.43137255 0.43137255]
 ...
 [0.4392157  0.43529412 0.43137255 ... 0.45490196 0.4509804  0.4509804 ]
 [0.44313726 0.44313726 0.4392157  ... 0.4509804  0.44705883 0.44705883]
 [0.44313726 0.4509804  0.4509804  ... 0.44705883 0.44705883 0.44313726]]

Matplotlib 已将每个通道的 8 位数据重新缩放为 0.0 到 1.0 之间的浮点数据,每个内部列表代表一个像素
对于 RGB 图像,有 3 个值。由于它是黑白图像,因此 R、G 和 B 都相似
对于 RGBA(其中 A 是 alpha 或透明度),每个内部列表有 4 个值,而简单的亮度图像只有一个值(因此只是一个 2-D 数组,而不是 3-D 数组)

## 将 numpy 数组绘制为图像

Matplotlib 中,可以使用 imshow() 函数来渲染图像数据生成的numpy数组

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
 
img = mpimg.imread('data.png')
img
#将伪彩色方案应用于图像图
lum_img = np.expand_dims(img, axis=2)
plt.imshow(lum_img)
 
plt.show()

[python]matplotlib_第29张图片

## 增加亮色

plt.imshow(lum_img,cmap='hot')

[python]matplotlib_第30张图片

imgplot = plt.imshow(lum_img)
imgplot.set_cmap('nipy_spectral')

[python]matplotlib_第31张图片

加入色标

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
 
img = mpimg.imread('data.png')
img
#将伪彩色方案应用于图像图
lum_img = np.expand_dims(img, axis=2)
plt.imshow(lum_img)
plt.colorbar()
plt.show()

[python]matplotlib_第32张图片

检查特定数据范围

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
 
img = mpimg.imread('data.png')
lum_img = np.expand_dims(img, axis=2)
 
plt.hist(lum_img.ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k')
 
plt.show()

[python]matplotlib_第33张图片

对比度

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
 
img = mpimg.imread('data.png')
lum_img = np.expand_dims(img, axis=2)
 
fig = plt.figure()
 
a = fig.add_subplot(1, 2, 1)
imgplot = plt.imshow(lum_img)
a.set_title('Before')
plt.colorbar(ticks=[0.1, 0.3, 0.5, 0.7], orientation='horizontal')
 
a = fig.add_subplot(1, 2, 2)
imgplot = plt.imshow(lum_img, clim=(0.0, 0.7))
# 也可以:
# imgplot = plt.imshow(lum_img)
# imgplot.set_clim(0.0, 0.7)
a.set_title('After')
plt.colorbar(ticks=[0.1, 0.3, 0.5, 0.7], orientation='horizontal')
 
plt.show()

[python]matplotlib_第34张图片

插值

import matplotlib.pyplot as plt
from PIL import Image
 
img = Image.open('data.png')
img.thumbnail((64, 64), Image.LANCZOS)
imgplot = plt.imshow(img)
 
plt.show()

[python]matplotlib_第35张图片

imgplot = plt.imshow(img, interpolation="nearest")

[python]matplotlib_第36张图片

双三次插值(bicubic)

imgplot = plt.imshow(img, interpolation="bicubic")

[python]matplotlib_第37张图片

完整实例

import numpy as np
import matplotlib.pyplot as plt
 
data = {'Barton LLC': 109438.50,
        'Frami, Hills and Schmidt': 103569.59,
        'Fritsch, Russel and Anderson': 112214.71,
        'Jerde-Hilpert': 112591.43,
        'Keeling LLC': 100934.30,
        'Koepp Ltd': 103660.54,
        'Kulas Inc': 137351.96,
        'Trantow-Barrows': 123381.38,
        'White-Trantow': 135841.99,
        'Will LLC': 104437.60}
group_data = list(data.values())
group_names = list(data.keys())
group_mean = np.mean(group_data)
 
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
plt.show()

[python]matplotlib_第38张图片

设置样式

import matplotlib.pyplot as plt 
print(plt.style.available)
['Solarize_Light2', '_classic_test_patch', '_mpl-gallery', '_mpl-gallery-nogrid', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-v0_8', 'seaborn-v0_8-bright', 'seaborn-v0_8-colorblind', 'seaborn-v0_8-dark', 'seaborn-v0_8-dark-palette', 'seaborn-v0_8-darkgrid', 'seaborn-v0_8-deep', 'seaborn-v0_8-muted', 'seaborn-v0_8-notebook', 'seaborn-v0_8-paper', 'seaborn-v0_8-pastel', 'seaborn-v0_8-poster', 'seaborn-v0_8-talk', 'seaborn-v0_8-ticks', 'seaborn-v0_8-white', 'seaborn-v0_8-whitegrid', 'tableau-colorblind10']
plt.style.use('fivethirtyeight') #样式设置成fivethirtyeight
fig, ax = plt.subplots()
ax.barh(group_names, group_data)

[python]matplotlib_第39张图片

保存图形

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
print(fig.canvas.get_supported_filetypes())
'''
{'eps': 'Encapsulated Postscript', 'jpg': 'Joint Photographic Experts Group', 
'jpeg': 'Joint Photographic Experts Group', 'pdf': 'Portable Document Format', 
'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics', 
'ps': 'Postscript', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 
'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', 
'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File Format'}
'''
{'eps': 'Encapsulated Postscript', 'jpg': 'Joint Photographic Experts Group', 'jpeg': 'Joint Photographic Experts Group', 'pdf': 'Portable Document Format', 'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics', 'ps': 'Postscript', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', 'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File Format', 'webp': 'WebP Image Format'}





"\n{'eps': 'Encapsulated Postscript', 'jpg': 'Joint Photographic Experts Group', \n'jpeg': 'Joint Photographic Experts Group', 'pdf': 'Portable Document Format', \n'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics', \n'ps': 'Postscript', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', \n'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', \n'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File Format'}\n"

[python]matplotlib_第40张图片

# 保存图形
fig.savefig('山月.png', transparent=False, dpi=80, bbox_inches="tight")

你可能感兴趣的:(python基础,python,matplotlib,开发语言)