matplotlib.pyplot_Matplotlib Pyplot教程
最近自己經常遇到matplotlib的OO API和pyplot包混亂不分的情況,所以抽時間好好把matplotlib的文檔讀了一下,下面是大概的翻譯和總結。很多基礎的東西還是要系統地掌握牢固哇~~另外一篇翻譯是
曲奇:matplotlib中文入門文檔(user guide)?zhuanlan.zhihu.commatplotlib.pyplot是一個函數的集合,每一個pyplot下面的函數都在figure上做一些動作。
pyplot的動作默認是在當前的Axes上。
import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4]) plt.ylabel('some numbers') plt.show()如果plot的參數是一個單獨的list或array,matplotlib認為它是y值,自動生成x軸從0開始。等價于plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
制定plot的顏色和線型
對于每一個x-y對,都有一個可選的參數,“顏色+線型”的字符串
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro') plt.axis([0, 6, 0, 20]) plt.show()根據這個文檔可以查看完整的線型和format: plot
axis函數則可以輸入[xmin, xmax, ymin, ymax],和其他控制axis的函數。
plot函數可以同時傳入多條線和參數
import numpy as np# evenly sampled time at 200ms intervals t = np.arange(0., 5., 0.2)# red dashes, blue squares and green triangles plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') plt.show()根據keyword參數plot
可以傳入字典或pd.DataFrame,np.recarray。matplotlib允許一個data參數。
然后用keyword指定x和y是哪些。
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']) * 100plt.scatter('a', 'b', c='c', s='d', data=data) plt.xlabel('entry a') plt.ylabel('entry b') plt.show()categorical variables
x軸可以是類別型參數
names = ['group_a', 'group_b', 'group_c'] values = [1, 10, 100]plt.figure(figsize=(9, 3))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()控制線的性質
有三種方法去控制線的性質:
plt.plot(x, y, linewidth=2.0)
line, = plt.plot(x, y, '-')
line.set_antialiased(False) # turn off antialiasing
lines = plt.plot(x1, y1, x2, y2)
# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
這是Line2D的參數列表
也可以通過調用step函數,傳入line或lines來獲取可以設置的屬性
In [69]: lines = plt.plot([1, 2, 3])In [70]: plt.setp(lines)alpha: floatanimated: [True | False]antialiased or aa: [True | False]...snip多figures和多Axes
pyplot是在當前figure和當前axes上工作的,通過gca可以拿到當前axes(是一個 matplotlib.axes.Axes實例),通過gcf 可以拿到當前figure實例(matplotlib.figure.Figure實例)。
以下是一個創建兩個subplot的實例。這里的figure函數可以不用調用的,默認會創建figure(1)。
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()如果不顯式調用subplot,默認是創建一個subplot(111),如果不手動指定任何axes。subplot指定numrows,numcols,plotnumber。subplot(211)等價于subplot(2,1,1)
能夠手動地任意擺放axes,給axes函數傳入位置[left, bottom, width, height]
# Creating a new full window axes plt.axes()# Creating a new axes with specified dimensions and some kwargs plt.axes((left, bottom, width, height), facecolor='w')可以創建多個figure,只要在figure()函數中傳入一個遞增的數字即可。
import matplotlib.pyplot as plt plt.figure(1) # the first figure plt.subplot(211) # the first subplot in the first figure plt.plot([1, 2, 3]) plt.subplot(212) # the second subplot in the first figure plt.plot([4, 5, 6])plt.figure(2) # a second figure plt.plot([4, 5, 6]) # creates a subplot(111) by defaultplt.figure(1) # figure 1 current; subplot(212) still current plt.subplot(211) # make subplot(211) in figure1 current plt.title('Easy as 1, 2, 3') # subplot 211 title能夠通過clf()函數清除當前figure或通過cla()函數清除當前axes。當圖片被顯式地關閉時(在python shell模式下),內存空間才會釋放。調用了show()之后,如果關閉了圖片,原先的figure和axes即釋放。
圖片上所有文本text信息
mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000)# the histogram of the data 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()所有的text函數都會返回一個matplotlib.text.Text 實例,這個實例能夠用于step的參數,并對實例設置屬性。
數學函數
plt.title(r'$sigma_i=15$')注解Annotating
需要指定被注解的位置xy(也就是箭頭指向的位置)和文本位置xytext
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),)plt.ylim(-2, 2) plt.show()對數和其他非線性軸
改變一個軸的scale
plt.xscale('log')# Fixing random state for reproducibility np.random.seed(19680801)# make up some data in the open interval (0, 1) 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))# plot with various axes scales plt.figure()# linear plt.subplot(221) plt.plot(x, y) plt.yscale('linear') plt.title('linear') plt.grid(True)# log 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', linthresh=0.01) plt.title('symlog') plt.grid(True)# logit plt.subplot(224) plt.plot(x, y) plt.yscale('logit') plt.title('logit') plt.grid(True) # Adjust the subplot layout, because the logit one may take more space # than usual, due to y-tick labels like "1 - 10^{-3}" plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,wspace=0.35)plt.show()參考
https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py
總結
以上是生活随笔為你收集整理的matplotlib.pyplot_Matplotlib Pyplot教程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c++输出小数点后几位_2.1 怎么在屏
- 下一篇: oracle中join另一个表后会查询不