matplotlib简单教程

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 np
import matplotlib.pyplot as plt

X = 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 np
import matplotlib.pyplot as plt

# Create a new figure of size 8x6 inches, using 100 dots per inch
plt.figure(figsize=(8, 6), dpi=80)

# Create a new subplot from a grid of 1x1
plt.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 limits
plt.xlim(-4.0, 4.0)

# Set x ticks
plt.xticks(np.linspace(-4, 4, 9))

# Set y limits
plt.ylim(-1.0, 1.0)

# Set y ticks
plt.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 np
import matplotlib.pyplot as plt

# Create a new figure of size 8x6 inches, using 100 dots per inch
plt.figure(figsize=(12, 6), dpi=80)

# Create a new subplot from a grid of 1x1
plt.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
plt.xlim(-4.0, 4.0)

# Set x ticks
plt.xticks(np.linspace(-4, 4, 9))

# Set y limits
plt.ylim(-1.0, 1.0)

# Set y ticks
plt.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 np
import matplotlib.pyplot as plt

# Create a new figure of size 8x6 inches, using 100 dots per inch
plt.figure(figsize=(10, 6), dpi=80)

# Create a new subplot from a grid of 1x1
plt.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 points
plt.xlim(X.min()*1.1, X.max()*1.1)

# Set x ticks
plt.xticks(np.linspace(-4, 4, 9))

# Set y limits to make some space in order to clearly see all data points
plt.ylim(S.min()*1.1, S.max()*1.1)

# Set y ticks
plt.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 np
import matplotlib.pyplot as plt

# Create a new figure of size 8x6 inches, using 100 dots per inch
plt.figure(figsize=(10, 6), dpi=80)

# Create a new subplot from a grid of 1x1
plt.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 points
plt.xlim(X.min()*1.1, X.max()*1.1)

# Set x ticks
plt.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 points
plt.ylim(S.min()*1.1, S.max()*1.1)

# Set y ticks
plt.yticks([-1, 0, 1])

# Save figure using 72 dots per inch
# plt.savefig('figures/1.jpg', dpi=72)

plt.show()

5

import numpy as np
import matplotlib.pyplot as plt

# Create a new figure of size 8x6 inches, using 100 dots per inch
plt.figure(figsize=(10, 6), dpi=80)

# Create a new subplot from a grid of 1x1
plt.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 points
plt.xlim(X.min()*1.1, X.max()*1.1)

# Set x ticks to use latex to allow for nice rendering of the label
plt.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 points
plt.ylim(S.min()*1.1, S.max()*1.1)

# Set y ticks to use latex to allow for nice rendering of the label
plt.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 np
import matplotlib.pyplot as plt

# Create a new figure of size 8x6 inches, using 100 dots per inch
plt.figure(figsize=(10, 6), dpi=80)

# Create a new subplot from a grid of 1x1
plt.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 area
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom') # default
ax.spines['left'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left') # default
ax.spines['bottom'].set_position(('data', 0))

# Set x limits to make some space in order to clearly see all data points
plt.xlim(X.min()*1.1, X.max()*1.1)

# Set x ticks to use latex to allow for nice rendering of the label
plt.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 points
plt.ylim(S.min()*1.1, S.max()*1.1)

# Set y ticks to use latex to allow for nice rendering of the label
plt.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 np
import matplotlib.pyplot as plt

# Create a new figure of size 8x6 inches, using 100 dots per inch
plt.figure(figsize=(10, 6), dpi=80)

# Create a new subplot from a grid of 1x1
plt.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 area
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom') # default
ax.spines['left'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left') # default
ax.spines['bottom'].set_position(('data', 0))

# Set x limits to make some space in order to clearly see all data points
plt.xlim(X.min()*1.1, X.max()*1.1)

# Set x ticks to use latex to allow for nice rendering of the label
plt.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 points
plt.ylim(S.min()*1.1, S.max()*1.1)

# Set y ticks to use latex to allow for nice rendering of the label
plt.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 np
import matplotlib.pyplot as plt

# Create a new figure of size 8x6 inches, using 100 dots per inch
plt.figure(figsize=(10, 6), dpi=80)

# Create a new subplot from a grid of 1x1
plt.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 area
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom') # default
ax.spines['left'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left') # default
ax.spines['bottom'].set_position(('data', 0))

# Set x limits to make some space in order to clearly see all data points
plt.xlim(X.min()*1.1, X.max()*1.1)

# Set x ticks to use latex to allow for nice rendering of the label
plt.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 points
plt.ylim(S.min()*1.1, S.max()*1.1)

# Set y ticks to use latex to allow for nice rendering of the label
plt.yticks([-1, 0, 1], ['$-1$', '$0$', '$1$'])

px = 2*np.pi/3
plt.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 inch
plt.savefig('figures/1.jpg', dpi=100)

plt.show()

9

import matplotlib.pyplot as plt
import matplotlib.gridspec as gs

G = 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.xaxis
plt.yticks([]) # plt-->ax1.yaxis
ax2.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) units
ax1 = 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 coordinates
ax2.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 np
import matplotlib.pyplot as plt

n = 256
X = 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 np
import matplotlib.pyplot as plt

n = 12
X = 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

import numpy as np
import matplotlib.pyplot as plt

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

17

import numpy as np
import matplotlib.pyplot as plt

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

18

Reference Tutorial

Here are more resources……

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值