Matplotlib之基本做图
Refer to 莫烦Python之Matplotlib
快速查看某种图的实现,https://matplotlib.org/gallery.html#widgets
1. Installation 安装
numpy is required before installing the ‘matplotlib’
On unix-like system, directly install these package(module) through pip
command
# python2
$ pip install numpy, matplotlib
# python3
$ pip3 install numpy, matplotlib
Personally, managing the python modules through Conda is highly recommended.
$ conda info -e
$ anaconda search conda numpy
2. Basic Operations 基本画图
-
Grammar
- similar to the function plot in MatLab
- 7 buttons are listed below the image, which provide som functions: the Subplot configuration Tool , Zoom Im, Reset, Move Save etc.
-
Coding Example
# import the modules import matplotlib.pyplot as plt import numpy as np # set up the variables x = np.linspace(-1, 1, 50) y = x ** 2 # plot it plt.plot(x, y) plt.show()
3. Figure 画多个图, 不同线性
-
draw multiple figures
pyplot.figure([num, figsize=(longth, width), ])
-
plot multiple lines on a figure
- invoke multiple
pyplot.plot(x,xx,)
functions with different styles, (color, marker, size, line style)
1 import numpy as np 2 import matplotlib.pyplot as plt 3 4 # data preparation 5 x = np.linspace(-1, 1, 50) 6 y1 = 2 * x + 1 7 y2 = x ** 2 8 y3 = np.sin(x) 9 11 # draw data 12 plt.figure(figsize=(5,5)) 13 plt.plot(x, y1, '-.r', linewidth=2, markersize=3) 14 plt.plot(x, y2) 15 16 plt.figure(num=5, figsize=[5,7]) 17 plt.plot(x, y3, color='y', linestyle='-.', linewidth=1.0) 18 19 plt.show()
- invoke multiple
4. Axis Setting 坐标轴
-
range
pyplot.xlim((x_min, x_max))
pyplot.ylim((y_min, y_max))
- ex:
pyplot.ylim((0, max(y) * 1.1))
-
label
pyplot.xlabel(str)
pyplot.ylabel(str)
- Ex:
pyplot.ylabel("Amplitute")
-
self-defined ticks
pyplot.xticks(lst)
pyplot.yticks(lst)
- Ex1:
pyplot.xticks(np.linspace(-1, 2, 5))
- Ex2:
pyplot.yticks([-1, 0, 1, 2,], [r"$so\ bad$", "normal", r"$good$", r"$exce\beta$"])
-
position of axis
- get handle of axis:
ax = pyplot.gca()
- access four axis:
ax.spines["top",'bottom','left','right']
,xxx.set_color('none')
,xxx.set_position(('data', data_value))
- set defualt x,y axis:
ax.xaxis.set_ticks_position('left')
ax.yaxis.set_ticks_position()
import matplotlib.pyplot as plt import numpy as np # data x = np.linspace(-3, 3, 50) y1 = x ** 2 y2 = 2 * x + 1 # basic plot plt.figure() plt.plot(x, y2) plt.plot(x, y1, color='red', linewidth=1.0, linestyle="--") # set label and range plt.xlim((-1, 2)) plt.ylim((-2, 3)) plt.xlabel("Axis x (m)") plt.ylabel("Axis Y ") # set self-defined ticks plt.xticks(np.linspace(-1, 2, 5)) plt.yticks([-2, -1.5, -1, 1.22, 3], [r'$so\ bad$', r'$bad$', r'$pretty\ normal$', "good", r"$very\ good$"]) # set axis color and position ax = plt.gca() # gca "get current axis" ax.spines["right"].set_color('none') ax.spines["top"].set_color('none') ax.spines["bottom"].set_position(("data", 0)) # outward, axes(percentage) ax.spines["left"].set_position(("data", 0 )) ax.xaxis.set_ticks_position("bottom") ax.yaxis.set_ticks_position("left") plt.show()
- get handle of axis:
5. Legend 图例
-
simply
-
set the attribute label when invoking the plot function
pyplot.plot(x, y, label="This is first line")
-
call the legend func
pyplot.legend()
-
-
personalize legend (advanced)
loc
: “upper right”, “lower left”, “best”handles
: pass in the lineslabels
: list of strings
line1, = pyplot.plot(x, y1) # note the comma line2, = pyplot.plot(x, y2) pyplot.legend(handles=[line1, line2], labels=["aaa", "bbb"], loc="best")
6. Annotation 注释
-
two ways
- pyplot.annotations()
- pyplot.text()
-
coding
import matplotlib.pyplot as plt import numpy as np x = np.linspace(-3, 3, 50) y = 2 * x + 1 plt.figure(num=1, figsize=(8,5),) plt.plot(x, y) ax=plt.gca() ax.spines["top"].set_color("none") ax.spines["right"].set_color("none") ax.xaxis.set_ticks_position("bottom") ax.yaxis.set_ticks_position("left") ax.spines["bottom"].set_position(("data", 0)) ax.spines["left"].set_position(("data", 0 )) # add notations x0 = 1 y0 = 2 * x0 + 1 plt.scatter(x0, y0, s=50, color="b") plt.plot([x0, x0], [0, y0], 'k--', linewidth=2.5) # method 1 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")) # method 2 plt.text(-3.7, 3, r"$Some\ text\ goes\ Here.\ \mu\ \sigma\ \alpha$", fontdict={"size":16, "color":'r'}) plt.show()
7. Tick 设置
-
Access & Set tick labels
ax = plt.gca()
ax.get_xticklabels() / ax.get_yticklabels()
xxx.set_fontsize()
xxx.set_bbox()
-
examples:
1 import matplotlib.pyplot as plt 2 import numpy as np 3 4 x = np.linspace(-3, 3, 50) 5 y = 0.1 * x 6 7 plt.figure() 8 plt.plot(x, y, linewidth=10) 9 10 ax=plt.gca() 11 ax.spines["top"].set_color("none") 12 ax.spines["right"].set_color("none") 13 ax.xaxis.set_ticks_position("bottom") 14 ax.yaxis.set_ticks_position("left") 15 ax.spines["bottom"].set_position(("data", 0)) 16 ax.spines["left"].set_position(("data", 0 )) 17 18 for label in ax.get_xticklabels() + ax.get_yticklabels(): 19 label.set_fontsize(12) 20 label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7)) 21 22 plt.show()
8. Subplot 多图合一
-
similar to what we did in MatLab, using
subplot
import matplotlib.pyplot as plt plt.figure(figsize=(10,10)) plt.subplot(2,2,1) plt.plot([0,1], [0,1]) plt.title('figure 1') plt.subplot(2,2,2) plt.plot([1,0], [0.5,1]) plt.title('figure 2') plt.subplot(223) plt.plot([1,0], [0,1]) plt.title('figure 3') plt.subplot(224) plt.plot([0,1], [0.5,1]) plt.title('figure 4') plt.figure(figsize=(10,5)) plt.subplot(2,1,1) plt.plot([0,1], [0,1]) plt.subplot(2,3,4) plt.plot([0,1], [0,1]) plt.subplot(2,3,5) plt.plot([0,1], [0,1]) plt.subplot(236) plt.plot([0,1], [0,1]) plt.show()
9. Grid 分格显示
-
3 methods
-
subplot2grid
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec plt.figure(figsize=(10,10)) # (3,3)-> shape of the whole grid # (0,0)-> specify where this plot begins # by default, colspan = rowspan = 1 ax1 = plt.subplot2grid((3,3), (0,0), colspan=3, rowspan=1) ax1.plot([1,0],[0,1]) ax1.set_title("figure 1") ax2 = plt.subplot2grid((3,3), (1,0), colspan=2) ax2.plot([1,0],[1,1]) ax2.set_title("figure 2") ax3 = plt.subplot2grid((3,3), (1,2), rowspan=2) ax3.plot([1,1],[0,1]) ax3.set_title("figure 3") ax4 = plt.subplot2grid((3,3), (2,0)) ax4.scatter(0,0, s=30, color='r') ax4.set_title("figure 4") ax5 = plt.subplot2grid((3,3), (2,1)) ax5.scatter(0,0, s=60, color='b') ax5.set_title("figure 5") plt.show()
-
gridspec (import matplotlib.gridspec as gridspec)
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec plt.figure(figsize=(10,10)) gs = gridspec.GridSpec(3,3) ax1 = plt.subplot(gs[0,:]) ax1.plot([1,0],[0,1]) ax1.set_title("figure 1") ax2 = plt.subplot(gs[1,:2]) ax2.plot([1,0],[1,1]) ax2.set_title("figure 2") ax3 = plt.subplot(gs[1:,2]) ax3.plot([1,1],[0,1]) ax3.set_title("figure 3") ax4 = plt.subplot(gs[2,0]) #ax4 = plt.subplot(gs[-1,0]) ax4.scatter(0,0, s=30, color='r') ax4.set_title("figure 4") ax5 = plt.subplot(gs[2,1]) #ax5 = plt.subplot(gs[-1,-2]) ax5.scatter(0,0, s=60, color='b') ax5.set_title("figure 5") plt.show()
-
easy to define structure (subplots)
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec f, ((ax11, ax12), (ax21, ax22)) = plt.subplots(2,2, sharex=True, sharey=True) ax11.scatter([0,1,2], [0, 1, 2]) plt.tight_layout() plt.show()
-
10. Second Axis 次坐标轴
-
twinx()
import matplotlib.pyplot as plt import numpy as np x = np.arange(0, 10, 0.1) y1 = 0.05 * x ** 2 y2 = -1 * y1 fig, ax1 = plt.subplots() ax2 = ax1.twinx() ax1.plot(x,y1, 'g-') ax2.plot(x,y2, 'b-.') ax1.set_xlabel("XX") ax1.set_ylabel("YY1", color='g') ax2.set_ylabel("YY2", color='b') plt.show()