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()

1

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()

2

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()

3

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()

4

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()

5

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()

6

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()

7

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()

8

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()

9

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()

10

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()

11

# 函数与坐标轴之间的区域进行填充,使用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()  

12

# 填充两个函数之间的区域,使用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()  

13

# 当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()  

14

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()

15

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()

16

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() 

17

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()

18

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()

19

阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 www.haoav99.com www.yyk8.cp pornxxxxx18year 国产开疱小学生 www.88887e.com 亚洲一本100vr keino 18 真实记录小萝莉被开处 janpen vidos wwwxxxx jixxxxxxxxx 强犴大全视频 18年新址 1849 cc 欠欠草 第0041章推倒林姨 带妻子玩3ip 教官把我顶得死去活来 www.44kxkx.com 我是你老师尽快拔出来呀 强犴视频免费 美国式禁恋的母亲 殴美伦里3000 www.67777.cc 小蝴蝶app(可以看很污的视频) 二中学生打野 宁陵初中女学生视频在线 97超人人澡l 18japanfist在线播放 www.88eyz.com 越南幼4399 www.xy4.app 儿子的计划1[67p] 医生把手伸入她早已湿透的小说1 要撑坏了爸爸 www.xvideos18.com 大叔1v1高甜肉 viddvidsvids中国女 近相亲母 第一福利网站 公婆边日边粗口 20岁女生下边都是黑的吗