Matplotlib

Basic

Import

from matplotlib import pyplot as plt

Build figure

fig = plt.figure(1)
fig = plt.figure(1, figsize=(10,10))    # set figure size

Tighten the layout

fig.tight_layout()

Build subplots

ax = plt.subplot(111)
ax = plt.subplot(211) # build two subplots and select the left one
ax = plt.subplot(111, projection='polar') # build polar subplot

Draw graphs

ax.plot()
ax.bar()
ax.hist()
ax.scatter()
ax.plot_date()

Show figure

fig.show()

Clear figure

fig.clf()

Save figure

plt.savefig('path/name.png')

Legend & Label & Tick & Grid

# title
ax.set_title('plot', fontsize=20)

# label
ax.set_xlabel('Threshold (m/s)')
ax.set_ylabel('Strom periods (hours)')

# ticks
ax.set_xticks(np.arange(0, 1.1, 0.1))
ax.set_yticks(np.arange(0, 1.1, 0.1))
ax.set_xticklabels(labels, size=9, rotation=15)

# axis limits
plt.xlim(0, 1)
# or
ax.set_xlim(0, 1)

# grid
ax.grid(True)
ax.grid(False)
ax.yaxis.grid(True)

# legend
ax.plot(xx, yy, label='plot1')
ax.legend(loc='lower left', frameon=False, fontsize=12)
# or
ax.legend(['line1', 'line2'])

Two y-axis

ax1 = plt.subplot(111)
ax1.plot(X1, Y, c='blue', label="X1")
ax2 = ax1.twinx()
ax2.plot(X2, Y, c='orange', label="X2")

Circle

circle = plt.Circle((x, y), radius, linestyle='solid', fill=False)
ax.add_artist(circle)

Annotate

ax.annotate('annotation',
    xy=(xx, yy),
    xycoords='data',
    xytext=(-30, -50),
    textcoords='offset points',
    fontsize=16,
    arrowprops=dict(arrowstyle="->",
        connectionstyle="arc3,rad=.2"
        )
    )

3D

# import and set interative 3D plot
%matplotlib notebook
from mpl_toolkits.mplot3d import Axes3D
# meshgrid
x_lin, y_lin = np.linspace(-1, 1, 101), np.linspace(-1, 1, 101)
xx, yy = np.meshgrid(x_lin, y_lin)
zz = xx**2 + yy**2
ax = fig.add_subplot(111, projection='3d')
ax.scatter(xx, yy, zz)
ax.plot_wireframe(xx, yy, zz)
ax.plot_surface(xx, yy, zz)

Animation

Import

from matplotlib.animation import FuncAnimation
from IPython.display import HTML
plt.rcParams['animation.ffmpeg_path'] = '/usr/local/bin/ffmpeg'

Example 1

fig, ax = plt.subplots()
line, = ax.plot(np.random.rand(10))
ax.set_ylim(0, 1)

def update(data):
    line.set_ydata(data)
    return line,

def data_gen():
    while True:
        yield np.random.rand(10)

anim = FuncAnimation(fig, update, data_gen, interval=100, frames=300, blit=True)

anim = FuncAnimation(fig,
    update, # 反复调用改变图形的函数
    data_gen,   # 数据生成器
    init_func=init, # 图像初始化
    frames=360, # 动画长度,一次循环包含的帧数,update函数中要传入frame
    T,   # 更新频率,以ms计
    blit=True   # True=更新所有点,False=仅更新产生变化的点,但mac须选False
    )
plt.show()
HTML(anim.to_html5_video()) # display
anim.save('anim.gif', writer='imagemagick', dpi=40) # save to gif

Example 2

fig = plt.figure(1)
ax = fig.add_subplot(111, projection='3d')

x, y, z = np.random.rand(3)
ax.scatter(x, y, z)

def update(*arg):
    x, y, z = np.random.rand(3)
    ax.scatter(x, y, z)

anim = FuncAnimation(fig, update)
fig.show()

Rotating view

def animate(frame):
    ax.view_init(elev=10., azim=frame)

Example 3

n = 5
XX, YY, ZZ = np.random.rand(3, n)
fig = plt.figure(1)
ax = fig.add_subplot(111, projection='3d')
ax.grid(False)
fig.tight_layout()

def init():
    ax.set_xlim(1.1 * min(XX), 1.1 * max(XX))
    ax.set_ylim(1.1 * min(YY), 1.1 * max(YY))
    ax.set_zlim(1.1 * min(ZZ), 1.1 * max(ZZ))
    ax.patch.set_facecolor('#FFFFFF')
    ax.set_axis_off()
    ax.scatter(XX, YY, ZZ, c='#002755')
    for i in range(n):
        for j in range(i+1,n):
            ax.plot((XX[i], XX[j]), 
                (YY[i], YY[j]), 
                (ZZ[i], ZZ[j]), 
                c='#A49EA7',
                linewidth=0.8)
    return ax,

def update(frame):
    ax.view_init(elev=10., azim=frame)
    return ax,

anim = FuncAnimation(fig, update, init_func=init, interval=10, frames=360)

Save

anim.save('anim.mp4', writer='ffmpeg', fps=30, dpi=40)
anim.save('anim.gif', writer='imagemagick', fps=30, dpi=40)

Mobius

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.tri as mtri
from matplotlib.animation import FuncAnimation

u = np.linspace(0, 2*np.pi, endpoint=True, num=50)
v = np.linspace(-1, 1, endpoint=True, num=10)
u, v = np.meshgrid(u, v)
u = u.flatten()
v = v.flatten()
xx_mobius = (1 + 0.5 * v * np.cos(u / 2.0)) * np.cos(u)
yy_mobius = (1 + 0.5 * v * np.cos(u / 2.0)) * np.sin(u)
zz_mobius = 0.5 * v * np.sin(u / 2.0)

theta = np.linspace(0, 4*np.pi, endpoint=True, num=100)
r = 0.2
xc = (1 + r * np.cos(theta / 2. + np.pi/2)) * np.cos(theta)
yc = (1 + r * np.cos(theta / 2. + np.pi/2)) * np.sin(theta)
zc = r * np.sin(theta / 2. + np.pi/2)

idx = 2
u2 = np.linspace(0, 2 * np.pi, 100)
v2 = np.linspace(0, np.pi, 100)
xx_ball = xc[idx] + r * np.outer(np.cos(u2), np.sin(v2))
yy_ball = yc[idx] + r * np.outer(np.sin(u2), np.sin(v2))
zz_ball = zc[idx] + r * np.outer(np.ones(np.size(u2)), np.cos(v2))

tri = mtri.Triangulation(u, v)
fig = plt.figure()
ax = plt.axes(projection='3d')
ax = plt.axes(projection='3d')
#ax.scatter(xc, yc, zc)
ax.plot_surface(xx_ball, yy_ball, zz_ball, color='b')
ax.plot_trisurf(xx_mobius, yy_mobius, zz_mobius,cmap="cool", triangles=tri.triangles, alpha=0.5)

ax.set_xlim(-1.1, 1.1)
ax.set_ylim(-1.1, 1.1)
ax.set_zlim(-1, 1)

def update(frame):
    idx = int(frame)
    u2 = np.linspace(0, 2 * np.pi, 100)
    v2 = np.linspace(0, np.pi, 100)
    xx_ball = xc[idx] + r * np.outer(np.cos(u2), np.sin(v2))
    yy_ball = yc[idx] + r * np.outer(np.sin(u2), np.sin(v2))
    zz_ball = zc[idx] + r * np.outer(np.ones(np.size(u2)), np.cos(v2))
    ax.plot_surface(xx_ball, yy_ball, zz_ball, color='b')

ani = FuncAnimation(fig, update, frames=np.arange(0, 100, 1) ,blit=False   , interval=1000)
ani.save('anim.mp4', writer='ffmpeg', fps=None, dpi=None)

Basemap

import

# import
from mpl_toolkits.basemap import Basemap

build projection

m = Basemap(llcrnrlon=-93.536379,
    llcrnrlat=16.179933,
    urcrnrlon=-82.002156,
    urcrnrlat=26.132693,
    resolution='i',
    projection='tmerc',
    lon_0=-87.0,
    lat_0=0.0
    )

project lon/lat to xx/yy

xx, yy = m(lon, lat)
df['xx'] = df.apply(lambda x: m(x['lon'], x['lat'])[0], axis=1)
df['yy'] = df.apply(lambda x: m(x['lon'], x['lat'])[1], axis=1)

draw map background

m.drawcoastlines(color='0.50', linewidth=0.6, zorder=0)
m.fillcontinents(color='#f2efe8', alpha=0.8, zorder=0)
m.drawmapboundary(fill_color='#b7d0cd', zorder=0)

Plotly

Install

pip install plotly==4.14.3

# Jupyter Notebook Support
pip install "notebook>=5.3" "ipywidgets>=7.5"

Quick Start

import plotly.graph_objects as go
fig = go.Figure(data=go.Bar(y=[2, 3, 1]))
fig.show()

Timeseries

Time Series and Date Axes in Python

import pandas as pd
df = pd.read_csv('data.csv')

import plotly.graph_objects as go
fig = go.Figure([go.Scatter(x=df['Date'], y=df['AAPL.High'])])
fig.show()

References