1.散點圖一
#導入繪製散點圖所需要的包import matplotlib.pyplot as pltfrom numpy.random import rand#生成繪圖所需的圖紙fig, ax = plt.subplots()#for循環遍歷紅青藍黃四種顏色for color in ['red', 'cyan', 'blue','yellow']:n = 750 #X = rand 返回一個在區間 (0,1) 內均勻分布的隨機數 #x=rand(1,8)產生1行8列的位於(0,1)區間的隨機數 #x, y = rand(2, n)表示x,y都返回2行n列的位於(0,1)區間的隨機數 x, y = rand(2, n) #scale表示隨機點的大小,這裡進行了隨機生成 scale = 200.0 * rand(n) #繪製散點圖,x,y坐標,顏色按照for循環中的四色進行變換 #設置透明度和點的邊緣色為無 ax.scatter(x, y, c=color, s=scale, label=color, alpha=0.3, edgecolors='none')#設置圖例和網格線ax.legend()ax.grid(True)plt.show()
2.填充標記
#python2裡面,dict.items返回的是數組,six.iteritems(dict)則返回生成器。意味著,dict很大的時候,後者不佔用內存。#python3 裡面, dict.items改變了默認實現,也返回生成器,因此six.iteritems退出了舞臺。from six import iteritemsimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.lines import Line2D#每條線上繪製三個點points = np.ones(3)#設置文本的格式,垂直方向是靠右對齊,水平方向是居中對齊,字體大小、種類設置text_style = dict(horizontalalignment='right', verticalalignment='center',fontsize=12, fontdict={'family': 'monospace'})marker_style = dict(linestyle=':', color='seagreen', markersize=10)#定義坐標軸的形式,去掉x,y坐標軸def format_axes(ax): ax.margins(0.2) ax.set_axis_off()#定義文本中去字符的形式def nice_repr(text): return repr(text).lstrip('u')#" / " 表示浮點數除法,返回浮點結果;#" // " 表示整數除法,返回不大於結果的一個最大的整數def split_list(a_list): i_half = len(a_list) // 2 return (a_list[:i_half], a_list[i_half:])#生成一個包含兩列內容的圖紙fig, axes = plt.subplots(ncols=2)#過濾掉的不常用的填充標記#使用iteritems來得到一個迭代器unfilled_markers = [m for m, func in iteritems(Line2D.markers) if func != 'nothing' and m not in Line2D.filled_markers]#[::1]中省略起止位置,步進為-1,python中步進為正,從左往右取,步進為負,從右往左取#即實現逆向排序unfilled_markers = sorted(unfilled_markers, key=lambda x: (str(type(x)), str(x)))[::-1]for ax, markers in zip(axes, split_list(unfilled_markers)): for y, marker in enumerate(markers): ax.text(-0.5, y, nice_repr(marker), **text_style) ax.plot(y * points, marker=marker, **marker_style) format_axes(ax)fig.suptitle('非填充標記', fontsize=14)#繪圖時正常顯示中文plt.rcParams['font.sans-serif'] = ['SimHei']fig, axes = plt.subplots(ncols=2)for ax, markers in zip(axes, split_list(Line2D.filled_markers)): for y, marker in enumerate(markers): ax.text(-0.5, y, nice_repr(marker), **text_style) ax.plot(y * points, marker=marker, **marker_style) format_axes(ax)fig.suptitle('填充標記', fontsize=14)plt.show()
3.橫(縱)向誤差圖
import numpy as npimport matplotlib.pyplot as plt#三個參數分別是起始點,終止點和步長x=np.arange(0.0,5,0.5)y=np.exp(-x**2)#誤差條設置error=0.1+0.5*x#繪圖是正常生成中文plt.rcParams['font.sans-serif'] = ['SimHei']#生成圖紙,繪製兩幅子圖,分成兩行,共享x軸坐標fig,(ax0,ax1)=plt.subplots(nrows=2,sharex=True)#繪製第一幅誤差條形圖,誤差條分布方向為縱向,上下誤差條對稱分布ax0.errorbar(x,y,yerr=error,fmt='-o')ax0.set_title('對稱的誤差條形圖')#以y(x)軸方向為例,設置向下(左)誤差條的長度lower_error=0.3*error#以y(x)軸方向為例,設置向上(右)誤差條的長度upper_error=error#得到一個誤差列表,為繪製非對稱的誤差條形圖做準備different_error=[lower_error,upper_error]#繪製第二幅誤差條形圖ax1.errorbar(x,y,xerr=different_error,fmt='o')ax1.set_title('非對稱的誤差條形圖')#轉變成對數刻度ax1.set_yscale('log')plt.show()