Data visualization: Matplotlib detailed explanation and actual combat

 1 Introduction to Matplotlib

 Matplotlib is one of the most commonly used visualization tools in Python, which can easily create massive types of 2D charts and some basic 3D charts.

Matplotlib provides an API interface for programming object-oriented drawing, which can easily realize the drawing of various images, and it can cooperate with Python GUI tools (such as PyQt, Tkinter, etc.) to embed graphics in applications. At the same time, Matplotlib also supports embedding in IPython shell, Jupyter notebook, and web application server in the form of scripts.

1.1 Matplotlib architecture composition

The matplotlib framework is divided into three layers. These three layers form a stack, and the upper layer can call the lower layer.

1.1.1 Script layer

Mainly used for visual programming, the pytplot module can provide us with an interface to deal with matplotlib. Graphics can be drawn by manipulating the entire package just by calling functions of the pyplot module.

  • Manipulate or modify the Figure object, such as creating a Figure object
  • Most of the work is dealing with the generation of graphics and coordinates of the sample files

1.1.2 Art layer

All visible elements in the graph belong to the Artist object, that is, all the elements that make up the graph such as the title, axis label, and scale are instances of the Artist object.

  • Figure: Refers to the entire graphic (including all elements, such as titles, lines, etc.).
  • Axes (coordinate system): axes is a sub-graph object, and the sub-graph object refers to the x and y axes. axes commonly used set_xlabel(), set_ylabel() to set the coordinate names of the x and y axes.
  • Axis (coordinate axis): An axis in the coordinate system, including size limits, ticks, and tick labels.

A figure (graph) can contain multiple axes (coordinate systems), but an axes can only belong to one figure. An axes (coordinate system) can contain multiple axes (coordinate axes), including two is the 2d coordinate system, and three is the 3d coordinate system.

1.1.3 Backend layer

The bottom layer of matplotlib implements a large number of abstract interface classes, and these APIs are used to implement each class of graphic elements at the bottom layer.

  • The FigureCanvas object implements the concept of a drawing area.
  • The Renderer object draws on the FigureCanvas.

1.2 Introduction to Pyplot

Graphical display of data through Pyplot can intuitively understand the distribution of data and better formulate learning methods. At the same time, it can also show the calculation method learned by our machine, and understand whether it matches the actual situation and other issues.

  • Pyplot is a sub-library of Matplotlib that provides a drawing API similar to MATLAB.
  • Pyplot is a commonly used drawing module, which makes it easy for users to draw 2D charts.
  • Pyplot contains a series of related functions for drawing functions, each of which will make some modifications to the current image, for example: mark the image, generate a new image, generate a new drawing area in the image, and so on.

The Pyplot drawing process is as follows:

2 Pyplot functions

Pyplot contains a series of related functions for drawing functions, each of which will make some modifications to the current image

  • plot(): used to draw line graphs and scatter plots
  • scatter(): used to draw a scatterplot
  • bar(): used to draw vertical and horizontal bar charts
  • hist(): used to draw a histogram
  • pie(): used to draw pie charts
  • imshow(): for drawing images
  • subplots(): used to create subgraphs

2.1 plt.plot parameter description

plt.plot(x,y,format_string,**kwargs)

The `plt.plot()` function is a function in the Matplotlib library for drawing line graphs, and it has several parameters that control various aspects of the plot. The following are some commonly used parameters:

  • x: list or array of x-axis data
  • y: list or array of y-axis data
  • linewidth: the width of the line, a floating point number from 0 to infinity, such as 2.5
  • color: The color of the line, which can be a string, tuple or RGBA value, representing different colors. For example: red 'red', green 'green', blue 'blue', black 'black', white 'white', gray 'gray', etc.; RGB tuple (0, 0, 1) means blue, RGBA tuple The group (0, 1, 0, 0.5) represents a semi-transparent green
  • linestyle: The style of the line, which can be a string, such as solid line '-', dashed line '--', dotted line ':', dashed line '-.', etc.

  '-': solid line

  '--': dotted line

  '-.': Dotted line

  ':': Dotted line

  '': no lines, only markers

  'None': No lines, no markers displayed

  ' ': No lines, no markers displayed

  • marker: the marker style of the data point
mark character illustrate mark character illustrate mark character illustrate
' . ' point marker ' 1 ' lower flower triangle ' h ' vertical hexagon
' , ' pixel tag ' 2 ' upper flower triangle ' H ' horizontal hexagon
' o ' solid circle ' 3 ' left flower triangle ' + ' cross mark
' v ' inverted triangle ' 4 ' right flower triangle ' x ' x mark
' ^ ' upper triangle ' s ' solid square ' D ' diamond mark
' > ' right triangle ' p ' solid pentagon ' d ' diamond mark
' < ' left triangle ' * ' star mark ' | ' line mark

  • markersize: The size of the marker, a floating point number from 0 to infinity, such as 7.5
  • label: String type, representing the label of the drawn line, displayed in the legend. e.g. Line 1
  • alpha: The transparency of lines and markers, a floating-point number from 0 to 1, indicating the transparency of lines and markers. e.g. 0.5
  • zorder: Integer type, indicating the number of layers of the drawing, the larger the value, the higher the number. For example 2

And some other parameters:

  • solid_capstyle: The style of the endpoint of the solid line, such as the normal straight style "butt", the rounded style "round", the beveled style "projecting", etc.
  • dash_capstyle: The style of dashed endpoints, similar to solid_capstyle
  • dash_joinstyle: The style of dashed joints, such as arc connection "round", oblique connection "bevel", acute angle connection "miter", etc.
  • solid_joinstyle: The style of the solid line connection, similar to dash_joinstyle
  • markevery: Mark every interval, can be a number, a tuple or a function, can be a number, a tuple or a function. For example: mark every other data point: markevery=2; start from the second, mark every 5 data points: markevery=(1, 5); control the marker according to the return value of a function position: markevery=lambda i: i%3==0

The `plt.plot()` function has many parameters, and different parameter combinations can achieve various effects.

2.2 plt.scatter parameter description

matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, *, edgecolors=None, plotnonfinite=False, data=None, **kwargs)
  • x, y → coordinates of scattered points, float or array-like, shape (n, )
  • s → area of ​​scattered points, float or array-like, shape (n, ), optional
  • c → the color of the scatter point (the default value is blue, 'b', other colors are the same as plt.plot( ))
  • marker → scatter point style (default value is solid circle, 'o', other styles are the same as plt.plot( ))
  • alpha → scatter transparency (the number between [0, 1], 0 means completely transparent, 1 means completely opaque)
  • linewidths → edge linewidths of the scatter points
  • edgecolors → edge colors of scatter points

2.3 plt.bar参数说明

bar(x, height, width=0.8, bottom=None, ***, align='center', data=None, **kwargs)
  • x represents the x coordinate, the data type is int or float type,
  • height indicates the height of the histogram, that is, the y coordinate value, and the data type is int or float type,
  • width indicates the width of the histogram, the value is between 0 and 1, and the default is 0.8
  • bottom The starting position of the histogram, that is, the starting coordinate of the y-axis,
  • align The center position of the histogram, "center", "lege" edge
  • color histogram color
  • edgecolor border color
  • linewidth border width
  • tick_label subscript label
  • log Histogram y week uses scientific calculation method, bool type
  • orientation Whether the histogram is vertical or horizontal, vertical: "vertical", horizontal bar: "horizontal"

 2.4 plt.hist parameter description

matplotlib.pyplot.hist(  
    x, bins=10, range=None, normed=False,   
    weights=None, cumulative=False, bottom=None,   
    histtype=u'bar', align=u'mid', orientation=u'vertical',   
    rwidth=None, log=False, color=None, label=None, stacked=False,   
    hold=None, **kwargs)  
  • x  : (n,) array or sequence of (n,) arrays, this parameter is to specify the data distributed by each bin (box), corresponding to the x-axis
  • bins  : integer or array_like, optional, this parameter specifies the number of bins (boxes), that is, how many bar charts there are in total
  • normed  : boolean, optional, If True, the first element of the return tuple will be the counts normalized to form a probability density, ie, n/(len(x)`dbin), this parameter specifies the density, that is, each bar The proportion of the graph, the default is 1
  • color  : color or array_like of colors or None, optional, this specifies the color of the bar chart

3.5 plt.pie parameter description

pyplot.pie(x, explode=None, labels=None, colors=None, autopct=None)
  • x: Array sequence, the array elements correspond to the number of fan-shaped areas.
  • labels: A sequence of list strings, with a label name for each fan-shaped area.
  • colors; Set the color for each fan-shaped area, and the default is automatically set according to the color cycle.
  • autopct: The format string "fmt%pct", sets the label of each slice using the percentage format and places it inside the slice.
  • pctdistance: Set the distance between the percentage label and the center of the circle;
  • labeldistance: Set the distance between each sector label (legend) and the center of the circle;
  • explode: Specifies the highlighting of certain parts of the pie chart, that is, an explosion; ()
  • shadow: Whether to add the shadow effect of the pie chart

2.6 plt.imshow parameter description

matplotlib.pyplot.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None,extent=None, shape=None, filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None, hold=None, data=None, **kwargs)
  • X : Image data. Supported array shapes are:

    • (M,N): Image with scalar data. Data visualization using colormaps.
    • (M, N, 3): Image (float or uint8) with RGB values.
    • (M, N, 4): Image (float or uint8) with RGBA values, i.e. including transparency.
      The first two dimensions (M, N) define the row and column of the image, i.e. the height and width of the image;
      RGB(A) values ​​should be in the range of floats [0, ..., 1], or
      integers [0, ... ,255]. Values ​​outside the range will be clipped to these bounds.
  • cmap: Map scalar data to a colormap, color defaults to :rc: image.cmap.
  • norm :~matplotlib.colors.Normalize, if using scalar data, Normalize will scale it within the data value of [0,1]. By default, the data range is mapped to the colorbar range using linear scaling. This parameter is ignored for RGB(A) data.

  • aspect : {'equal', 'auto'} or float, optional, controls the aspect ratio of the axes. This parameter can distort the image, i.e. the pixels are not square. equal: Make sure the aspect ratio is 1, the pixels will be square. (Unless the pixel size explicitly becomes non-square in the data, the coordinates use extent). auto: Change the image aspect ratio to match the axes aspect ratio. Typically, this will result in non-square pixels.

  • interpolation: str, the interpolation method used, supported values ​​are: 'none', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos'. If interpolation = 'none', no interpolation is performed

  • alpha: alpha value, between 0 (transparent) and 1 (opaque). This parameter is ignored for RGBA input data.

  • vmin, vmax : scalar, vmin , vmax * are ignored if *norm parameter is used . vmin, vmax are used in conjunction with norm to normalize luminance data.
  • origin : {'upper', 'lower'}, place the [0,0] index of the array at the upper-left or lower-left corner of the axis. 'upper' is usually used for matrices and images. Note that the vertical axis points up to "down" but down to "up".
  • extent: (left, right, bottom, top) the position of the lower left and upper right corners in data coordinates. If None, the image is positioned such that the pixel center falls on a zero-based (row, column) index.

2.7 plt.subplots参数说明

matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)
  • nrows, ncols: integer, optional parameter, default is 1. Indicates the number of rows and columns of the subplot grid ( grid ).
  • sharex, sharey: boolean or {'none', 'all', 'row', 'col'}, default: False, controls attribute sharing between x(sharex) or y(sharey) axes:

   1. True or 'all': x or y axis properties will be shared among all subplots.

   2. False or 'none': Each subplot's x or y axis is an independent part
   3.'row': Each subplot shares a row (row) on one x or y axis
   4.'col': Each subplot Share columns on an x ​​or y axis

When the subplots have a shared column on the x-axis ('col'), only the x tick markers of the bottom subplot are visible. Similarly, when the subplots have a shared row on the y-axis ('row'), only the y tick markers of the subplots in the first column are visible.

  • squeeze: Boolean type, optional parameter, default: True.

If True, extra dimensions are extruded from the returned Axes (axes) object.
        If only one subplot is constructed (nrows=ncols=1), the result is a single Axes object returned as a scalar.
        For N*1 or 1*N subgraphs, return a 1D array.
        For N*M, N>1 and M>1 returns a 2D array.
If False, do not squeeze: returns a 2D array of Axes instances, even if it ends up being 1x1.

  • subplot_kw: dictionary type, optional parameters. Pass the keys of the dictionary to add_subplot() to create each subplot.
  • gridspec_kw dictionary type, optional parameter. Pass the keys of the dictionary to the GridSpec constructor to create subgraphs and place them in the grid.
  • **fig_kw: Pass all detailed keyword arguments to the figure() function 

3 Matplotlib plotting

3.1 Draw a straight line

import matplotlib.pyplot as plt

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

We provide a list or array to the plot command, matplotlib thinks this sequence is the value on the Y axis, and will automatically generate the value on the X axis. Because the range in python starts from 0, so the X axis starts from 0, and the length is the same as the Y length, which is [0,1,2,3], so it is displayed as follows:

 3.2 Draw a polyline

import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.ylabel('some numbers')
plt.show()

The parameters of the plot can be any number. The above parameters represent (x,y) pairs, (1,1)(2,4)(3,9)(4,16). There is a third optional parameter, which is in string format, indicating the color and line type. It is a combination of the color string and the line's type string. By default, this string parameter is 'b-', representing a solid blue line. Displayed as follows:

 3.3 Drawing a point set

import matplotlib.pyplot as plt

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

'ro' means that the red circle draws the above set of points, which is displayed as follows:

3.4 Drawing multiple point sets through numpy data

import numpy as np
import matplotlib.pyplot as plt

# 0到5之间每隔0.2取一个数
t = np.arange(0., 5., 0.2)

# 红色的破折号,蓝色的方块,绿色的三角形
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

Construct three sets of numpy data and display them in different styles, as shown below:

 3.5 Drawing multiple figures (figures) and multiple coordinate systems (axes)

import numpy as np
import matplotlib.pyplot as plt

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("2subplot")
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()

All the drawing commands of pyplot are applied to the current figure (figure) and the current coordinate system (axes), and draw a figure in the two coordinate systems respectively, as shown below:

 3.6 Drawing Histogram

import numpy as np
import matplotlib.pyplot as plt

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

# 直方图
n, bins, patches = plt.hist(x, 50, normed=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()

The text() command can be used to add text at any position, and xlabel(), ylabel(), title() are used to add text at the specified position. All text() commands return a matplotlib.text.Text instance, you can customize the text style in text() through keyword parameters, or you can customize the text style through setp(): 

t = plt.xlabel('my data', fontsize=14, color='red')
setp(t,color='blue')

import matplotlib.pyplot as plt
import numpy as np

# 生成三组随机数据
data1 = np.random.normal(0, 1, 1000)
data2 = np.random.normal(2, 1, 1000)
data3 = np.random.normal(-2, 1, 1000)

# 绘制直方图
plt.hist(data1, bins=30, alpha=0.5, label='Data 1')
plt.hist(data2, bins=30, alpha=0.5, label='Data 2')
plt.hist(data3, bins=30, alpha=0.5, label='Data 3')

# 设置图表属性
plt.title('matplotlib hist() ')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.grid()
plt.legend()

# 显示图表
plt.show()

3.7 Draw Y-axis graphs using different scales

import numpy as np
import matplotlib.pyplot as plt

# 在区间[0,1]制造一些数据
# np.random.normal为高斯分布
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))

# 创建一个窗口
plt.figure(1)

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

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

# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.05)
plt.title('symlog')
plt.grid(True)

# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)

plt.show()

 matplotlib.pylot provides not only linear coordinates, but also logarithmic and logit coordinates. Such coordinates are useful when the dimensions of the data span many orders of magnitude

 3.8 Drawing a scatterplot

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

x = np.random.randn(50)
y = np.random.randn(50)  
color =  np.random.rand(50)
changecolor = colors.Normalize(vmin=0.4, vmax=0.8)
plt.scatter(x, y, c=color, s=60, alpha=0.3, cmap='viridis',norm=changecolor)
plt.colorbar()  # 显示颜色条
plt.show()

The parameters vmin and vmax are the minimum and maximum values ​​of the data range to be set respectively (note: after setting, the original value greater than vmax will be "pulled down" to vmax; the original value smaller than vmin will be "pulled up" to vmin) 

class matplotlib.colors.Normalize(vmin=None, vmax=None)

The color table is as follows:

 

import numpy as np
import matplotlib.pyplot as plt

# 随机数生成器的种子
np.random.seed(2)
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = (30 * np.random.rand(N))**2  # 0 to 15 point radii

plt.scatter(x, y, s=area, c=colors, alpha=0.5) # 设置颜色及透明度

plt.title("matplotlib Scatter ") # 设置标题
plt.colorbar()

plt.show()

 

 3.9 Drawing a Pie Chart

import matplotlib.pyplot as plt

#定义饼的标签,
labels = ['one','two','three','four','five','other']

#每个标签所占的数量
x = [200,500,1200,7000,200,900]

#饼图分离
explode = (0.03,0.05,0.06,0.04,0.08,0.1)

#设置阴影效果
#plt.pie(x,labels=labels,autopct='%3.2f%%',explode=explode,shadow=True)

plt.pie(x,labels=labels,autopct='%3.2f%%',explode=explode, labeldistance=1.35, pctdistance=1.2)
plt.legend()
plt.show()

 3.10 Drawing a bar chart

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

# 将全局的字体设置为黑体
matplotlib.rcParams['font.family'] = 'SimHei'

# 数据
N = 5
y = [20, 10, 30, 25, 15]
x = np.arange(N)

# 绘图 x x轴, height 高度, 默认:color="blue", width=0.8
p1 = plt.bar(x, height=y, width=0.5, )

# 展示图形
plt.show()

"""
    水平条形图,需要修改以下属性
    orientation="horizontal"
"""
import numpy as np
import matplotlib.pyplot as plt
 
# 数据
N = 5
x = [20, 10, 30, 25, 15]
y = np.arange(N)
 
# 绘图 x= 起始位置, bottom= 水平条的底部(左侧), y轴, height 水平条的宽度, width 水平条的长度
p1 = plt.bar(x=0, bottom=y, height=0.5, width=x, orientation="horizontal")
 
# 展示图形
plt.show()

import numpy as np
import matplotlib.pyplot as plt

# 设置画布颜色为 blue
plt.style.use("seaborn-v0_8-whitegrid")
fig, ax = plt.subplots()


# y 轴数据
data = [[5,25,50,20],
        [4,23,51,17],
        [6,22,52,19]]

X = np.arange(4)
width=0.25

plt.bar(X+width*0, data[0], color = 'darkorange', width = width,label = 'A')
plt.bar(X+width*1, data[1], color = 'steelblue', width =width,label="B")
plt.bar(X+width*2, data[2], color = 'violet', width = width,label = 'C')


# 添加文字描述
W = [width*0,width*1,width*2]# 偏移量
for i in range(3):
    for a,b in zip(X+W[i],data[i]):#zip拆包
        plt.text(a,b,"%.0f"% b,ha="center",va= "bottom")#格式化字符串,保留0位小数
 
plt.xlabel("Group")
plt.ylabel("Num")

# 在(0,48)这个位置,显示note 这个值
plt.text(1,48,"note",fontsize=15, ha='left', rotation=15, wrap=True)   


# family参数是一个字体参数
plt.text(1.5,32,"deep",fontsize=15, ha='left', rotation=15, wrap=True,
         bbox=dict(boxstyle='round,pad=0.5', fc='yellow', ec='k',lw=1 ,alpha=0.5))   


plt.legend()
plt.show()

 

 3.11 Drawing multiple subplots

import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(3, 3, figsize=(6,6))

fig.text(0.5, 0, 'x', ha='center')
fig.text(0, 0.5, 'y', va='center')

x = np.linspace(0, 2*np.pi, 50, endpoint=False)
sins = np.sin(x)
coss = np.cos(x)

ax[1][1].plot(x, sins, 'r', alpha=0.5, lw=0.5, ls='-', marker='+', label='sin')
ax2 = ax[1][1].twinx()
ax2.plot(x, coss, 'g', alpha=0.5, lw=0.5, ls='-', marker='+', label='cos')
for tl in ax2.get_yticklabels():
    tl.set_color("r")
    
plt.tight_layout()
plt.show()

 3.12 Draw a time-varying graph

import random
import time
 
import matplotlib.pyplot as plt
from pylab import mpl
 
mpl.rcParams["font.sans-serif"] = ["SimHei"]  # 设置显示中文字体
mpl.rcParams["axes.unicode_minus"] = False  # 设置正常显示符号
 
x = range(1, 101)
times = [random.randint(10, 200) for i in range(100)]
plt.figure(figsize=(15, 5), dpi=80)  # 创建画布
plt.plot(x, times, color='r', linestyle='-', label='t = 2', marker='v')  # 绘制折线图,点划线
 
plt.legend(loc=0)  # 显示图例
# 描述信息
plt.xlabel("设备数/个")
plt.ylabel("时间/s")
plt.title("时间变化图", fontsize=18)
 
plt.savefig("./time.jpg")  # 保存至指定位置
plt.show()  # 显示图像

3.13 Draw multiple pictures to display

# opencv显示
import cv2
# plt显示
from PIL import Image
import matplotlib.pyplot as plt


PATH = 'D:/dataset/cat_dog/valid/3.jpg'
plt.rcParams['font.sans-serif'] = ['SimHei']  # 显示中文

plt.subplot(1, 3, 1)
im = Image.open(PATH)
plt.imshow(im)
plt.xlabel('原图')

plt.subplot(1, 3, 2)
im = cv2.imread(PATH, 0)  # 参数0为灰度显示,参数1为RGB显示
plt.imshow(im, cmap='gray')
plt.xlabel('单通道图')

plt.subplot(1, 3, 3)
im = cv2.imread(PATH, 0)  # 参数0为灰度显示,参数1为RGB显示
im = cv2.equalizeHist(im)  # 直方图均衡
plt.imshow(im, cmap='gray')
plt.xlabel('直方图')

plt.show()

 3.14 Draw 3D graph

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# 生成3D figure
fig = plt.figure()
ax = Axes3D(fig, auto_add_to_figure=False)
fig.add_axes(ax)

# X, Y value
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X ** 2 + Y ** 2)

Z = np.sin(R)

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'), edgecolor='k')
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap='rainbow')

ax.set_zlim(-2, 2)
plt.show()

 

 

import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#定义坐标轴
fig = plt.figure()
ax1 = plt.axes(projection='3d')
#ax = fig.add_subplot(111,projection='3d')  #这种方法也可以画多个子图
#定义三维数据
xx = np.arange(-5,5,0.5)
yy = np.arange(-5,5,0.5)
X, Y = np.meshgrid(xx, yy)
Z = np.sin(X)+np.cos(Y)
#作图
ax1.plot_surface(X,Y,Z)
ax1.contour(X,Y,Z, zdim='z',offset=-2,cmap='rainbow')   #等高线图,要设置offset,为Z的最小值

fig = plt.figure()  #定义新的三维坐标轴
ax3 = plt.axes(projection='3d')
#定义三维数据
xx = np.arange(-5,5,0.5)
yy = np.arange(-5,5,0.5)
X, Y = np.meshgrid(xx, yy)
Z = np.sin(X)+np.cos(Y)
#作图
ax3.plot_surface(X,Y,Z,cmap='rainbow')
ax3.contour(X,Y,Z, zdim='z',offset=-2,cmap='rainbow')   #等高线图,要设置offset,为Z的最小值
plt.show()

 3.15 Adding comments to drawings

import matplotlib.pyplot as plt
import numpy as np

fig, geeeks = plt.subplots()

t = np.arange(0.0, 5.0, 0.001)
s = np.cos(3 * np.pi * t)
line = geeeks.plot(t, s, lw=2)

# Annotation
geeeks.annotate('Local Max', xy=(3.3, 1),
                xytext=(3, 1.8),
                arrowprops=dict(facecolor='green',
                                shrink=0.05), )

geeeks.set_ylim(-2, 2)

# Plot the Annotation in the graph
plt.show()

The annotate() method adds annotations, there are two points to note: the place that needs to be annotated, use the xy parameter to point out, and the position where the annotation text is placed, use the parameter xytext to specify the position, both parameters are (x ,y) tuple, where the coordinates used by xy and xytext are the coordinates according to the scale of the XY axis, called data coordinates.

 

import numpy as np 
import matplotlib.pyplot as plt 
  
x = np.arange(0, 10, 0.005) 
y = np.exp(-x / 3.) * np.sin(3 * np.pi * x) 
  
fig, ax = plt.subplots() 
ax.plot(x, y) 
ax.set_xlim(0, 10) 
ax.set_ylim(-1, 1) 
  
# Setting up the parameters 
xdata, ydata = 5, 0
xdisplay, ydisplay = ax.transData.transform((xdata, ydata)) 
  
bbox = dict(boxstyle ="round", fc ="0.8") 
arrowprops = dict( 
    arrowstyle = "->", 
    connectionstyle = "angle, angleA = 0, angleB = 90,\ 
    rad = 10") 
  
offset = 72
  
# Annotation 
ax.annotate('data = (%.1f, %.1f)'%(xdata, ydata), 
            (xdata, ydata), xytext =(-2 * offset, offset), 
            textcoords ='offset points', 
            bbox = bbox, arrowprops = arrowprops) 
  
  
disp = ax.annotate('display = (%.1f, %.1f)'%(xdisplay, ydisplay), 
            (xdisplay, ydisplay), xytext =(0.5 * offset, -offset), 
            xycoords ='figure pixels', 
            textcoords ='offset points', 
            bbox = bbox, arrowprops = arrowprops) 
  
# To display the annotation 
plt.show()

 

 

Guess you like

Origin blog.csdn.net/lsb2002/article/details/132058305