matplotlib简单教程
来源:互联网 发布:yum 不支持python 2.7 编辑:程序博客网 时间:2024/06/01 09:21
Simple plot
In this section, we want to draw the cosine and sine functions on the same plot. Starting from the default settings, we’ll enrich the figure step by step to make it nicer.
import numpy as npimport matplotlib.pyplot as pltX = np.linspace(-np.pi, np.pi, 256)C, S = np.cos(X), np.sin(X)plt.plot(X, C)plt.plot(X, S)plt.show()
Postscript: Matplotlib comes with a set of default settings that allow customizing all kinds of properties. You can control the defaults of almost every property in matplotlib: figure size and dpi, line width, color and style, axes, axis and grid properties, text and font properties and so on.
import numpy as npimport matplotlib.pyplot as plt# Create a new figure of size 8x6 inches, using 100 dots per inchplt.figure(figsize=(8, 6), dpi=80)# Create a new subplot from a grid of 1x1plt.subplot(111)X = np.linspace(-np.pi, np.pi, 256)C, S = np.cos(X), np.sin(X)# Plot cosine using blue color with a continuous line of width 1 (pixels)plt.plot(X, C, color='b', linewidth=1.0, linestyle='-')# Plot sine using green color with a continuous line of width 1 (pixels)plt.plot(X, S, color='g', linewidth=1.0, linestyle='-')# Set x limitsplt.xlim(-4.0, 4.0)# Set x ticksplt.xticks(np.linspace(-4, 4, 9))# Set y limitsplt.ylim(-1.0, 1.0)# Set y ticksplt.yticks(np.linspace(-1.0, 1.0, 5))# Save figure using 72 dots per inch# plt.savefig('../figures/1.jpg', dpi=72)plt.show()
import numpy as npimport matplotlib.pyplot as plt# Create a new figure of size 8x6 inches, using 100 dots per inchplt.figure(figsize=(12, 6), dpi=80)# Create a new subplot from a grid of 1x1plt.subplot(111)X = np.linspace(-np.pi, np.pi, 256)C, S = np.cos(X), np.sin(X)# Plot cosine using blue color with a continuous line of width 1 (pixels)plt.plot(X, C, color='b', linewidth=3.5, linestyle='-')# Plot sine using green color with a continuous line of width 1 (pixels)plt.plot(X, S, color='g', linewidth=2.5, linestyle='-')# Set x limitsplt.xlim(-4.0, 4.0)# Set x ticksplt.xticks(np.linspace(-4, 4, 9))# Set y limitsplt.ylim(-1.0, 1.0)# Set y ticksplt.yticks(np.linspace(-1.0, 1.0, 5))# Save figure using 72 dots per inch# plt.savefig('figures/1.jpg', dpi=72)plt.show()
import numpy as npimport matplotlib.pyplot as plt# Create a new figure of size 8x6 inches, using 100 dots per inchplt.figure(figsize=(10, 6), dpi=80)# Create a new subplot from a grid of 1x1plt.subplot(111)X = np.linspace(-np.pi, np.pi, 256)C, S = np.cos(X), np.sin(X)# Plot cosine using blue color with a continuous line of width 1 (pixels)plt.plot(X, C, color='b', linewidth=3.5, linestyle='-')# Plot sine using green color with a continuous line of width 1 (pixels)plt.plot(X, S, color='g', linewidth=2.5, linestyle='-')# Set x limits to make some space in order to clearly see all data pointsplt.xlim(X.min()*1.1, X.max()*1.1)# Set x ticksplt.xticks(np.linspace(-4, 4, 9))# Set y limits to make some space in order to clearly see all data pointsplt.ylim(S.min()*1.1, S.max()*1.1)# Set y ticksplt.yticks(np.linspace(-1.0, 1.0, 5))# Save figure using 72 dots per inch# plt.savefig('figures/1.jpg', dpi=72)plt.show()
import numpy as npimport matplotlib.pyplot as plt# Create a new figure of size 8x6 inches, using 100 dots per inchplt.figure(figsize=(10, 6), dpi=80)# Create a new subplot from a grid of 1x1plt.subplot(111)X = np.linspace(-np.pi, np.pi, 256)C, S = np.cos(X), np.sin(X)# Plot cosine using blue color with a continuous line of width 1 (pixels)plt.plot(X, C, color='b', linewidth=3.5, linestyle='-')# Plot sine using green color with a continuous line of width 1 (pixels)plt.plot(X, S, color='g', linewidth=2.5, linestyle='-')# Set x limits to make some space in order to clearly see all data pointsplt.xlim(X.min()*1.1, X.max()*1.1)# Set x ticksplt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])# Set y limits to make some space in order to clearly see all data pointsplt.ylim(S.min()*1.1, S.max()*1.1)# Set y ticksplt.yticks([-1, 0, 1])# Save figure using 72 dots per inch# plt.savefig('figures/1.jpg', dpi=72)plt.show()
import numpy as npimport matplotlib.pyplot as plt# Create a new figure of size 8x6 inches, using 100 dots per inchplt.figure(figsize=(10, 6), dpi=80)# Create a new subplot from a grid of 1x1plt.subplot(111)X = np.linspace(-np.pi, np.pi, 256)C, S = np.cos(X), np.sin(X)# Plot cosine using blue color with a continuous line of width 1 (pixels)plt.plot(X, C, color='b', linewidth=3.5, linestyle='-')# Plot sine using green color with a continuous line of width 1 (pixels)plt.plot(X, S, color='g', linewidth=2.5, linestyle='-')# Set x limits to make some space in order to clearly see all data pointsplt.xlim(X.min()*1.1, X.max()*1.1)# Set x ticks to use latex to allow for nice rendering of the labelplt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], ['$-\pi$', '$-\pi/2$', '$0$', '$\pi/2$', '$\pi$'])# Set y limits to make some space in order to clearly see all data pointsplt.ylim(S.min()*1.1, S.max()*1.1)# Set y ticks to use latex to allow for nice rendering of the labelplt.yticks([-1, 0, 1], ['$-1$', '$0$', '$1$'])# Save figure using 72 dots per inch# plt.savefig('figures/1.jpg', dpi=72)plt.show()
import numpy as npimport matplotlib.pyplot as plt# Create a new figure of size 8x6 inches, using 100 dots per inchplt.figure(figsize=(10, 6), dpi=80)# Create a new subplot from a grid of 1x1plt.subplot(111)X = np.linspace(-np.pi, np.pi, 256)C, S = np.cos(X), np.sin(X)# Plot cosine using blue color with a continuous line of width 1 (pixels)plt.plot(X, C, color='b', linewidth=3.5, linestyle='-')# Plot sine using green color with a continuous line of width 1 (pixels)plt.plot(X, S, color='g', linewidth=2.5, linestyle='-')# Spines are the lines connecting the axis tick marks and noting the boundaries of the data areaax = plt.gca()ax.spines['right'].set_color('none')ax.spines['top'].set_color('none')ax.xaxis.set_ticks_position('bottom') # defaultax.spines['left'].set_position(('data', 0))ax.yaxis.set_ticks_position('left') # defaultax.spines['bottom'].set_position(('data', 0))# Set x limits to make some space in order to clearly see all data pointsplt.xlim(X.min()*1.1, X.max()*1.1)# Set x ticks to use latex to allow for nice rendering of the labelplt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], ['$-\pi$', '$-\pi/2$', '$0$', '$\pi/2$', '$\pi$'])# Set y limits to make some space in order to clearly see all data pointsplt.ylim(S.min()*1.1, S.max()*1.1)# Set y ticks to use latex to allow for nice rendering of the labelplt.yticks([-1, 0, 1], ['$-1$', '$0$', '$1$'])# Save figure using 72 dots per inch# plt.savefig('figures/1.jpg', dpi=72)plt.show()
import numpy as npimport matplotlib.pyplot as plt# Create a new figure of size 8x6 inches, using 100 dots per inchplt.figure(figsize=(10, 6), dpi=80)# Create a new subplot from a grid of 1x1plt.subplot(111)X = np.linspace(-np.pi, np.pi, 256)C, S = np.cos(X), np.sin(X)# Plot cosine using blue color with a continuous line of width 1 (pixels)plt.plot(X, C, color='b', linewidth=3.5, linestyle='-', label='cosine')# Plot sine using green color with a continuous line of width 1 (pixels)plt.plot(X, S, color='g', linewidth=2.5, linestyle='-', label='sine')# Spines are the lines connecting the axis tick marks and noting the boundaries of the data areaax = plt.gca()ax.spines['right'].set_color('none')ax.spines['top'].set_color('none')ax.xaxis.set_ticks_position('bottom') # defaultax.spines['left'].set_position(('data', 0))ax.yaxis.set_ticks_position('left') # defaultax.spines['bottom'].set_position(('data', 0))# Set x limits to make some space in order to clearly see all data pointsplt.xlim(X.min()*1.1, X.max()*1.1)# Set x ticks to use latex to allow for nice rendering of the labelplt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], ['$-\pi$', '$-\pi/2$', '$0$', '$\pi/2$', '$\pi$'])# Set y limits to make some space in order to clearly see all data pointsplt.ylim(S.min()*1.1, S.max()*1.1)# Set y ticks to use latex to allow for nice rendering of the labelplt.yticks([-1, 0, 1], ['$-1$', '$0$', '$1$'])plt.legend(loc='upper left', frameon=False) # keyword argument frameon mean, whether wrap(enclose) legend or not# Save figure using 72 dots per inch# plt.savefig('figures/1.jpg', dpi=72)plt.show()
import numpy as npimport matplotlib.pyplot as plt# Create a new figure of size 8x6 inches, using 100 dots per inchplt.figure(figsize=(10, 6), dpi=80)# Create a new subplot from a grid of 1x1plt.subplot(111)X = np.linspace(-np.pi, np.pi, 256)C, S = np.cos(X), np.sin(X)# Plot cosine using blue color with a continuous line of width 1 (pixels)plt.plot(X, C, color='b', linewidth=3.5, linestyle='-', label='cosine', alpha=.3)# Plot sine using green color with a continuous line of width 1 (pixels)plt.plot(X, S, color='g', linewidth=2.5, linestyle='-', label='sine', alpha=.7)# Spines are the lines connecting the axis tick marks and noting the boundaries of the data areaax = plt.gca()ax.spines['right'].set_color('none')ax.spines['top'].set_color('none')ax.xaxis.set_ticks_position('bottom') # defaultax.spines['left'].set_position(('data', 0))ax.yaxis.set_ticks_position('left') # defaultax.spines['bottom'].set_position(('data', 0))# Set x limits to make some space in order to clearly see all data pointsplt.xlim(X.min()*1.1, X.max()*1.1)# Set x ticks to use latex to allow for nice rendering of the labelplt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], ['$-\pi$', '$-\pi/2$', '$0$', '$\pi/2$', '$\pi$'])# Set y limits to make some space in order to clearly see all data pointsplt.ylim(S.min()*1.1, S.max()*1.1)# Set y ticks to use latex to allow for nice rendering of the labelplt.yticks([-1, 0, 1], ['$-1$', '$0$', '$1$'])px = 2*np.pi/3plt.plot([px, px], [0, np.cos(px)], color='b', linestyle='--', linewidth=1.5)plt.scatter([px,],[np.cos(px)], s=66, c='b')plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$', xy=(px, np.cos(px)), xycoords='data', xytext=(-90, -50), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))plt.plot([px, px], [0, np.sin(px)], color='g', linestyle='--',linewidth=1.5)plt.scatter([px], [np.sin(px)], s=66, c='g')plt.annotate(s=r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$', xy=(px, np.sin(px)), xytext=(10, 20), xycoords='data', textcoords='offset points', arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.1'))# Devil is in the details(make it nicer)for label in ax.get_xticklabels() + ax.get_yticklabels(): ## ??? hava no effect label.set_fontsize(16) label.set_bbox(dict(facecolor='w', edgecolor='None', alpha=0.65 ))plt.legend(loc='upper left', frameon=False) # keyword argument frameon mean, whether wrap(enclose) legend or not# Save figure using 72 dots per inchplt.savefig('figures/1.jpg', dpi=100)plt.show()
import matplotlib.pyplot as pltimport matplotlib.gridspec as gsG = gs.GridSpec(3, 3)ax1 = plt.subplot(G[0, :])ax1.xaxis.set_ticks([])ax1.yaxis.set_ticks([])ax1.text(x=0.5, y=0.5, s='Axes 1', horizontalalignment='center',verticalalignment='center',size=24,alpha=.5)ax2 = plt.subplot(G[1:, 0])plt.xticks([]) # plt-->ax1.xaxisplt.yticks([]) # plt-->ax1.yaxisax2.text(0.5, 0.5, 'Axes 2', color='r', ha='left', va='bottom', fontsize=20, alpha=.6)ax3 = plt.subplot(G[1, 1])plt.xticks([])plt.yticks([])plt.text(0.5, 0.5, 'Axes 3', color='g', ha='center', va='center', size=20, alpha=.8)ax4 = plt.subplot(G[1, -1])plt.xticks([])plt.yticks([])plt.text(0.5, .5, 'Axes 4', color='b', ha='right', va='top', size=24, alpha=.3)ax5 = plt.subplot(G[-1, 1:])plt.xticks([])plt.yticks([])plt.text(0.5, 0.5, 'Axes 5', color='y', ha='center', va='baseline', size=26, alpha=.9)plt.show()
import matplotlib.pyplot as plt# fig = plt.figure(num=1, figsize=(6, 4), dpi=100) # generate a axes# axes(rect, facecolor='w')`` where *rect* = [left, bottom, width, height] in normalized (0, 1) unitsax1 = plt.axes([.1, .1, .8, .8])# plt.xticks([])# plt.yticks([])plt.text(0.6,0.6, 'axes([0.1,0.1,.8,.8])',color='r', ha='center',va='center',size=20,alpha=.5)ax2 = plt.axes([.2, .2, .3, .3]) # absolute coordinatesax2.text(.2, .2, 'axes 2', color='b', size=26)plt.show()
# 函数与坐标轴之间的区域进行填充,使用fill函数import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 5 * np.pi, 1000) y1 = np.sin(x) y2 = np.sin(2 * x) plt.fill(x, y1, color = "g", alpha = 0.3) plt.fill(x, y2, color = "b", alpha = 0.3) plt.show()
# 填充两个函数之间的区域,使用fill_between函数import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 5 * np.pi, 1000) y1 = np.sin(x) y2 = np.sin(2 * x) plt.plot(x, y1, c = "g") plt.plot(x, y2, c = 'r') # fill_between 填充两个函数之间的区域 # 两个函数之间的区域用黄色填充 plt.fill_between(x, y1, y2, facecolor = "yellow") plt.grid(which='major', axis='x', linestyle=':', color='r')plt.grid(which='major', axis='y', linestyle='-.', color='b')plt.show()
# 当y1在y2上方的时候,填充为蓝色,# 当y2在y1上方的时候,填充为黄色,# 在fill_between中使用where语句进行填充import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 5 * np.pi, 1000) y1 = np.sin(x) y2 = np.sin(2 * x) plt.plot(x, y1, c = "g") plt.plot(x, y2, c = 'r') # interpolate 自动填充空白,当x取得离散点差距较大时, # 显示的时候两个函数之间的区域可能有空白存在,interpolate 就是用来填充这部分区域 plt.fill_between(x, y1, y2, where= y1 >= y2, facecolor="blue", interpolate=False) plt.fill_between(x, y1, y2, where= y2 > y1, facecolor="yellow", interpolate=True) plt.show()
import numpy as npimport matplotlib.pyplot as pltn = 256X = np.linspace(-np.pi, np.pi, n)Y = np.sin(2*X)plt.plot(X, Y+1, color='b', linestyle='-', alpha=.8)plt.plot(X, Y-1, color='b', linestyle='-', alpha=.8)plt.fill_between(X, y1=1, y2=Y+1, color='r', alpha=.26)plt.fill_between(X, Y-1, y2=-1, where=Y-1>-1, color='c')plt.fill_between(X, Y-1, y2=-1, where=Y-1<-1, color='m')plt.savefig('figures')plt.show()
import numpy as npimport matplotlib.pyplot as pltn = 12X = np.arange(n)Y1 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n)Y2 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n)plt.axes([0.025,0.025,0.95,0.95])plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white', align='edge')plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white', align='edge')for x,y in zip(X,Y1): plt.text(x+0.4, y+0.05, '%.2f' % y, ha='center', va='bottom')for x,y in zip(X,Y2): plt.text(x+0.4, -y-0.05, '%.2f' % y, ha='center', va='top')plt.xlim(-.5,n), plt.xticks([])plt.ylim(-1.25,+1.25), plt.yticks([])plt.savefig('figures/bar.png', dpi=126)plt.show()
from pylab import * from matplotlib.ticker import MultipleLocator, FormatStrFormatter xmajorLocator = MultipleLocator(20) #将x主刻度标签设置为20的倍数 xmajorFormatter = FormatStrFormatter('%1.1f') #设置x轴标签文本的格式 xminorLocator = MultipleLocator(5) #将x轴次刻度标签设置为5的倍数 ymajorLocator = MultipleLocator(0.5) #将y轴主刻度标签设置为0.5的倍数 ymajorFormatter = FormatStrFormatter('%1.1f') #设置y轴标签文本的格式 yminorLocator = MultipleLocator(0.1) #将此y轴次刻度标签设置为0.1的倍数 t = arange(0.0, 100.0, 1) s = sin(0.1*pi*t)*exp(-t*0.01) ax = subplot(111) #注意:一般都在ax中设置,不再plot中设置 plot(t,s,'--b*') #设置主刻度标签的位置,标签文本的格式 ax.xaxis.set_major_locator(xmajorLocator) ax.xaxis.set_major_formatter(xmajorFormatter) ax.yaxis.set_major_locator(ymajorLocator) ax.yaxis.set_major_formatter(ymajorFormatter) #显示次刻度标签的位置,没有标签文本 ax.xaxis.set_minor_locator(xminorLocator) ax.yaxis.set_minor_locator(yminorLocator) ax.xaxis.grid(True, which='major') #x坐标轴的网格使用主刻度 ax.yaxis.grid(True, which='minor') #y坐标轴的网格使用次刻度 show()
import numpy as npimport matplotlib.pyplot as pltax = plt.axes([0.025,0.025,0.95,0.95])ax.set_xlim(0,40)ax.set_ylim(0,10)ax.xaxis.set_major_locator(plt.MultipleLocator(10))ax.xaxis.set_minor_locator(plt.MultipleLocator(2))ax.yaxis.set_major_locator(plt.MultipleLocator(2))ax.yaxis.set_minor_locator(plt.MultipleLocator(.5))ax.grid(which='major', axis='x', linewidth=0.75, linestyle='-.', color='0.75')# ax.grid(which='minor', axis='x', linewidth=0.25, linestyle='-', color='0.75')# ax.grid(which='major', axis='y', linewidth=0.75, linestyle='-', color='0.75')ax.grid(which='minor', axis='y', linewidth=0.25, linestyle='-.', color='0.75')# ax.set_xticklabels([])# ax.set_yticklabels([])# savefig('../figures/grid_ex.png',dpi=48)plt.show()
import numpy as npimport matplotlib.pyplot as pltfig = plt.figure()fig.subplots_adjust(bottom=0.025, left=0.025, top = 0.975, right=0.975)plt.subplot(2,1,1)plt.xticks([]), plt.yticks([])plt.subplot(2,3,4)plt.xticks([]), plt.yticks([])plt.subplot(2,3,5)plt.xticks([]), plt.yticks([])plt.subplot(2,3,6)plt.xticks([]), plt.yticks([])# plt.savefig('../figures/multiplot_ex.png',dpi=48)plt.show()
阅读全文