import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import matplotlib as mpl
print(mpl.__version__)
3.2.0
The pyplot API is generally less-flexible than the object-oriented API. Most of the function calls you see here can also be called as methods from an Axes object.
# https://matplotlib.org/3.1.3/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py
x = np.linspace(0, 10*np.pi, 100)
y1 = 2 * np.cos(x)
y2 = np.cos(0.5 * x)
y3 = np.sin(x)
plt.figure(figsize = (15, 7))
plt.plot(x, y1, 'r--', x, y2, 'bs', x, y3, 'g^')
[<matplotlib.lines.Line2D at 0xad43848>, <matplotlib.lines.Line2D at 0xad43a88>, <matplotlib.lines.Line2D at 0xad43e08>]
dat = {'x1': np.arange(50),
'u1': np.random.randint(0, 50, 50),
'u2': np.random.randn(50)}
dat['y1'] = dat['x1'] + 10 * dat['u1']
dat['y2'] = np.abs(dat['u2']) * 100
plt.scatter('x1', 'y1', c = 'u2', s = 'u1',data = dat,)
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()
x = np.linspace(0, 30, 300)
u = 30*np.random.randn(300)
y = 3 + 5 * x + u
colorN = np.random.randint(0, 50, 300)
sizeN = 100 * np.random.randn(300)
plt.figure(figsize = (15, 7))
plt.scatter(x, y, c = colorN, s = sizeN)
plt.title('I am from Matplotlib', size = 20)
plt.xlabel('X-axis', size = 18)
plt.ylabel('Y-axis', size = 18)
plt.savefig('pic1.jpg')
plt.show()
city = ['Helsinki', 'London', 'NYC', 'Warsaw', 'Chongqing']
popu = [100, 800, 850, 170, 880]
plt.figure(figsize = (16, 7))
plt.subplot(1, 3, 1)
plt.bar(city, popu)
plt.subplot(1, 3, 2)
plt.plot(city, popu)
plt.subplot(1, 3, 3)
plt.scatter(city, popu, s = 500)
plt.suptitle('Population of City', fontsize = 20)
Text(0.5, 0.98, 'Population of City')
setp() is the set property function.
x1 = np.arange(0, 10 ,.1)
y1 = np.cos(x1)
y2 = np.sin(x1)
line1 = plt.plot(x1, y1)
plt.setp(line1, color='r', linewidth=4.0,
alpha = 0.5, animated = True, dash_capstyle = 'projecting',
label = 'I am the first line',linestyle = '--')
line2 = plt.plot(x1, y2)
plt.setp(line2, color='b', linewidth=4.0,
marker = '+', markeredgecolor = 'r', markeredgewidth = 3 ,markerfacecolor = 'b', markersize = 10)
plt.legend()
<matplotlib.legend.Legend at 0xc1b7848>
plt.setp(line1) # get all callable properties
agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha: float animated: bool antialiased or aa: bool clip_box: `.Bbox` clip_on: bool clip_path: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None] color or c: color contains: callable dash_capstyle: {'butt', 'round', 'projecting'} dash_joinstyle: {'miter', 'round', 'bevel'} dashes: sequence of floats (on/off ink in points) or (None, None) drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default' figure: `.Figure` fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'} gid: str in_layout: bool label: object linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} linewidth or lw: float marker: marker style markeredgecolor or mec: color markeredgewidth or mew: float markerfacecolor or mfc: color markerfacecoloralt or mfcalt: color markersize or ms: float markevery: None or int or (int, int) or slice or List[int] or float or (float, float) path_effects: `.AbstractPathEffect` picker: float or callable[[Artist, Event], Tuple[bool, dict]] pickradius: float rasterized: bool or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: {'butt', 'round', 'projecting'} solid_joinstyle: {'miter', 'round', 'bevel'} transform: `matplotlib.transforms.Transform` url: str visible: bool xdata: 1D array ydata: 1D array zorder: float
MATLAB is using the concept of current figure and axes, pyplot borrowed this concept as well.
def f(t):
return np.exp(-t) * np. cos(3 * np.pi * t/2)
t1 = np.arange(0, 5, 0.1)
t2 = np.arange(0, 5, 0.3)
plt.figure(figsize = (15, 7)) # it is optional, since figure(1) will be created by default
plt.subplot(2,1,1)
plt.plot(t1, f(t1))
plt.scatter(t1, f(t1), s = 100, c = 'g')
plt.subplot(2,1,2)
plt.plot(t2, np.cos(t2), linestyle = '--', linewidth = 5, c = 'pink')
[<matplotlib.lines.Line2D at 0xc21f908>]
plt.figure(1)
plt.subplot(2,1,1)
plt.plot([1, 3, 9, 27])
plt.subplot(2,1,2)
plt.plot(x, y)
plt.figure(2, figsize = (10, 3))
plt.plot([3, 17, 29, 45, 91])
plt.figure(3)
plt.subplot(2,3,1)
plt.subplot(2,3,2)
plt.subplot(2,3,3)
plt.title('I am title')
Text(0.5, 1.0, 'I am title')
plt.close()
mu, sigma = 170, 3
x = 170 + sigma * np.random.randn(1000)
plt.figure(figsize = (15, 7))
h, bins, patches = plt.hist(x, 50, density=1, facecolor='purple', alpha=0.75) # bins is the location of bins, h is the height
plt.grid(True)
plt.xlabel('Height', fontsize = 15)
plt.ylabel('Percentage', fontsize = 15)
plt.text(162, 0.13, r'$\mu = 170$', fontsize = 15)
plt.text(162, 0.145, r'$\sigma = 3$', fontsize = 15)
plt.axis([155, 185, 0, 0.17])
plt.title(r'Height Distribution of $\mu = 170, \sigma = 3$', fontsize = 18)
Text(0.5, 1.0, 'Height Distribution of $\\mu = 170, \\sigma = 3$')
plt.plot(h) # n is the height of the bar
[<matplotlib.lines.Line2D at 0xade36c8>]
for i in patches:
print(i)
Rectangle(xy=(161.036, 0), width=0.38128, height=0.00262275, angle=0) Rectangle(xy=(161.418, 0), width=0.38128, height=0.00786824, angle=0) Rectangle(xy=(161.799, 0), width=0.38128, height=0.010491, angle=0) Rectangle(xy=(162.18, 0), width=0.38128, height=0.00524549, angle=0) Rectangle(xy=(162.562, 0), width=0.38128, height=0.00786824, angle=0) Rectangle(xy=(162.943, 0), width=0.38128, height=0.010491, angle=0) Rectangle(xy=(163.324, 0), width=0.38128, height=0.00786824, angle=0) Rectangle(xy=(163.705, 0), width=0.38128, height=0.0262275, angle=0) Rectangle(xy=(164.087, 0), width=0.38128, height=0.0183592, angle=0) Rectangle(xy=(164.468, 0), width=0.38128, height=0.020982, angle=0) Rectangle(xy=(164.849, 0), width=0.38128, height=0.0340957, angle=0) Rectangle(xy=(165.23, 0), width=0.38128, height=0.0340957, angle=0) Rectangle(xy=(165.612, 0), width=0.38128, height=0.0445867, angle=0) Rectangle(xy=(165.993, 0), width=0.38128, height=0.0603232, angle=0) Rectangle(xy=(166.374, 0), width=0.38128, height=0.0524549, angle=0) Rectangle(xy=(166.756, 0), width=0.38128, height=0.0839279, angle=0) Rectangle(xy=(167.137, 0), width=0.38128, height=0.0944189, angle=0) Rectangle(xy=(167.518, 0), width=0.38128, height=0.0865506, angle=0) Rectangle(xy=(167.899, 0), width=0.38128, height=0.0970416, angle=0) Rectangle(xy=(168.281, 0), width=0.38128, height=0.110155, angle=0) Rectangle(xy=(168.662, 0), width=0.38128, height=0.107533, angle=0) Rectangle(xy=(169.043, 0), width=0.38128, height=0.144251, angle=0) Rectangle(xy=(169.425, 0), width=0.38128, height=0.139006, angle=0) Rectangle(xy=(169.806, 0), width=0.38128, height=0.128515, angle=0) Rectangle(xy=(170.187, 0), width=0.38128, height=0.10491, angle=0) Rectangle(xy=(170.568, 0), width=0.38128, height=0.13376, angle=0) Rectangle(xy=(170.95, 0), width=0.38128, height=0.118024, angle=0) Rectangle(xy=(171.331, 0), width=0.38128, height=0.120646, angle=0) Rectangle(xy=(171.712, 0), width=0.38128, height=0.118024, angle=0) Rectangle(xy=(172.093, 0), width=0.38128, height=0.125892, angle=0) Rectangle(xy=(172.475, 0), width=0.38128, height=0.0734369, angle=0) Rectangle(xy=(172.856, 0), width=0.38128, height=0.0760596, angle=0) Rectangle(xy=(173.237, 0), width=0.38128, height=0.0655687, angle=0) Rectangle(xy=(173.619, 0), width=0.38128, height=0.0917961, angle=0) Rectangle(xy=(174, 0), width=0.38128, height=0.0550777, angle=0) Rectangle(xy=(174.381, 0), width=0.38128, height=0.0445867, angle=0) Rectangle(xy=(174.762, 0), width=0.38128, height=0.031473, angle=0) Rectangle(xy=(175.144, 0), width=0.38128, height=0.031473, angle=0) Rectangle(xy=(175.525, 0), width=0.38128, height=0.0262275, angle=0) Rectangle(xy=(175.906, 0), width=0.38128, height=0.010491, angle=0) Rectangle(xy=(176.288, 0), width=0.38128, height=0.0236047, angle=0) Rectangle(xy=(176.669, 0), width=0.38128, height=0.010491, angle=0) Rectangle(xy=(177.05, 0), width=0.38128, height=0.0157365, angle=0) Rectangle(xy=(177.431, 0), width=0.38128, height=0.00262275, angle=0) Rectangle(xy=(177.813, 0), width=0.38128, height=0.00262275, angle=0) Rectangle(xy=(178.194, 0), width=0.38128, height=0, angle=0) Rectangle(xy=(178.575, 0), width=0.38128, height=0, angle=0) Rectangle(xy=(178.957, 0), width=0.38128, height=0, angle=0) Rectangle(xy=(179.338, 0), width=0.38128, height=0, angle=0) Rectangle(xy=(179.719, 0), width=0.38128, height=0.00524549, angle=0)
plt.subplot(1,1,1)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, linewidth = 2)
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='red', shrink=0.05, edgecolor = 'red',headwidth = 40,
width = 8),
)
plt.ylim(-2, 2)
plt.show()
# subplots_adjust
# left = 0.125 # the left side of the subplots of the figure
# right = 0.9 # the right side of the subplots of the figure
# bottom = 0.1 # the bottom of the subplots of the figure
# top = 0.9 # the top of the subplots of the figure
# wspace = 0.2 # the amount of width reserved for space between subplots,
# # expressed as a fraction of the average axis width
# hspace = 0.2 # the amount of height reserved for space between subplots,
# # expressed as a fraction of the average axis height
from matplotlib.ticker import NullFormatter
y = np.random.normal(loc = 0, scale = 1, size = 1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))
plt.figure(figsize = (15, 10))
plt.subplot(2, 2, 1)
plt.plot(x, y)
plt.title('linear')
plt.grid(True)
plt.subplot(2, 2, 2)
plt.plot(x, y)
plt.title('Log')
plt.yscale('log')
plt.grid(True)
plt.gca().yaxis.set_minor_formatter(NullFormatter())
plt.subplot(2, 2, 3)
plt.plot(x, y)
plt.title('Logit')
plt.yscale('logit')
plt.grid(True)
plt.gca().yaxis.set_minor_formatter(NullFormatter())
# symmetric log
plt.subplot(2, 2, 4)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.01)
plt.title('Symlog')
plt.grid(True)
plt.subplots_adjust(top=0.90, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
wspace=0.35)
From this here on, we will be mostly using OOP approach for plotting.
t = np.arange(0, 3, 0.1)
s = np.cos(2 * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel = 'time', ylabel = 'voltage', title ='Cool Electricity Plot')
ax.grid()
x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z =(Z1 - Z2) * 2
fig, ax = plt.subplots()
# interpolation options:
#'none', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36',
#'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom',
#'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos'.
im = ax.imshow(Z, interpolation = 'gaussian', cmap ='summer', origin = 'lower', extent =[-3, 3, -3, 3])
################### Set Font First #############################
import matplotlib.font_manager as font_manager
fontGotham = font_manager.FontProperties(family='Gotham',
weight='bold',
style='normal', size=16)
# the family name can be checked in the property of the font file in 'Control Panel' in Windows OS
fontStayWildy = font_manager.FontProperties(family='Stay Wildy Personal Use Only',
weight='bold',
style='normal', size=16)
fontWildOne = font_manager.FontProperties(family='Wild Ones',
weight='bold',
style='normal', size=16)
fontRavie = font_manager.FontProperties(family='RAVIE',
weight='bold',
style='normal', size=16)
fontSimp = font_manager.FontProperties(family='Simplicity',
weight='bold',
style='normal', size=16)
fontForte = font_manager.FontProperties(family='Forte',
weight='bold',
style='normal', size=16)
fontFixe = font_manager.FontProperties(family='Fixedsys',
weight='bold',
style='normal', size=16)
fontAlgerian = font_manager.FontProperties(family='Algerian',
weight='bold',
style='normal', size=16)
fontBlackAdd = font_manager.FontProperties(family='Blackadder',
weight='bold',
style='normal', size=16)
#################################################################
x = np.arange(1, 30, 0.2)
u = np.random.randn(len(x))
u1 = np.random.randn(len(x))
y = 3 + 6 * x + 20 * u
y1 = 2 + 4 * x + 10 * u1
v = np.random.rand(len(x))
#################################################################
fig, ax = plt.subplots(nrows = 3, ncols = 3, figsize = (18, 13))
plt.subplots_adjust(hspace = 0.5)
#################################################################
# the size is proportional to v's absolute value
# and the annotation text color is random from the uniform distribution
ax[0, 0].scatter(x, y, c = v, s = 50 * np.abs(u), alpha = 0.8, edgecolor = None)
# We can choose the location of title by using (x = , y = )
ax[0, 0].set_title('Colorful Scatter Plot', fontproperties = fontStayWildy,
fontsize = 30, x = 0.3, y = 1.05)
ax[0, 0].annotate('I am a point', xy = (x[10], y[10]), xytext = (5, 150), color = (v[9], v[10], v[11]), fontsize = 15,
arrowprops=dict(facecolor='pink', shrink=0.1, edgecolor = 'pink' ,headwidth = 10, width = 1))
ax[0, 0].set_xlabel('X-Axis', fontsize = 15)
ax[0, 0].set_ylabel('Y-Axis', fontsize = 15)
# In order not to let the label overlap the X-axis, reset the location, it is the relative pct location to the X-axis
ax[0, 0].xaxis.set_label_coords(0.5, -0.1)
#################################################################
ax[0, 1].grid(True,color='pink', linestyle='-', linewidth=2)
sns.scatterplot(x, y, ax = ax[0, 1])
sns.scatterplot(x, y1, ax = ax[0, 1])
ax[0, 1].set_title('Seaborn Scatter Plot', fontproperties = fontWildOne,
fontsize = 30, x = 0.5, y = 1.05)
#################################################################
ax_list = ['top','right','bottom','left']
ax[0, 2].hist(u, bins = 12, color = (0.8, .3, .3, 0.5))
ax[0, 2].set_xlim([-5, 5])
ax[0, 2].set_ylim([0, 40])
# use loop to deepen the color of axis and thicken the linewidth of axis
i_thick = 1
i_color = .19
for i in ax_list:
ax[0, 2].spines[i].set_color((.1, 0.1, 1 - i_color))
ax[0, 2].spines[i].set_linewidth(i_thick)
i_thick += 2
i_color += 0.15
ax[0, 2].tick_params(axis = 'x', color = 'red', labelsize = 20) # change tick color and labelsize
ax[0, 2].tick_params(axis = 'y', colors = 'red', length = 20,
direction = 'in') # change both tick and tick label color, and add tick length
ax[0, 2].set_title('Happy Histogram', fontproperties = fontRavie,
fontsize = 30, x = 0.5, y = 1.05)
ax[0, 2].title.set_color([0.8, .3, .3, 0.5])
#################################################################
sns.distplot(u, ax = ax[1, 0], bins = 15,
rug = True, vertical = True,
color = 'r')
ax[1, 0].set_title('Seaborn KDE', fontproperties = fontSimp,
fontsize = 30, x = 0.5, y = 1.05)
#################################################################
from statsmodels.distributions.empirical_distribution import ECDF
# Return the Empirical CDF of an array as a step function.
ecdf = ECDF(u)
ax[1, 1].plot(ecdf.x, ecdf.y, linewidth = 3, color = 'r')
ax[1, 1].set_title('Statsmodel and \n Seaborn Emperical CDF', fontproperties = fontForte, fontsize = 30)
kwargs = {'cumulative': True}
sns.distplot(u, ax = ax[1, 1], hist_kws=kwargs)
sns.distplot(u, ax = ax[1, 1])
#################################################################
# We use scipy's stats module
ax[1, 2].plot(sp.stats.cumfreq(u, 10)[0]/len(u), linewidth = 3) # normalise the frequency count
ax[1, 2].set_title('Scipy CumFreq \n and CumHist Plot', fontproperties = fontGotham,
fontsize = 20, x = 0.5, y = 1.05)
ax[1, 2].title.set_color([0.6, .3, .8, 0.8])
ax[1, 2].hist(u, density = True, cumulative = True, histtype = 'step', linewidth = 3)
ax[1, 2].set_facecolor([0.3, 0.3, 0.3])
ax[1, 2].grid(True, linestyle='--', linewidth = 2, color = 'white')
#################################################################
A = np.zeros((5, 10))
for i in range(0, 5):
A[i] = np.random.normal(loc = i, scale = 1, size = (10))
col_mean = np.mean(A, axis = 1)
col_mean = col_mean[:,np.newaxis]
A = np.concatenate((A,col_mean),axis=1)
df = pd.DataFrame(A)
df.rename(columns = {10: 'mean'}, inplace = True)
std = np.zeros((5, 1))
for i in range(0,df.shape[0]):
std[i] = np.std(df.iloc[i,0:9])
std = pd.DataFrame(std)
df['std'] = std
ax[2, 0].errorbar(list(df.index), df['mean'], yerr = df['std'], fmt = 'o', capsize = 5, capthick = 2)
ax[2, 0].set_title('I am Crazy Error Bars', fontproperties = fontFixe,
fontsize = 20, x = 0.5, y = 1.05)
ax[2, 0].yaxis.grid(True, linestyle='--', linewidth = 2, color = 'red')
#################################################################
# we use the data generated above
# any data outside of 1.5*IQR will be shown indiviually as points
ax[2, 1].boxplot(df, notch = True, sym = '+')
ax[2, 1].set_title('Noteched Boxplot', fontproperties = fontAlgerian,
fontsize = 30, x = 0.5, y = 1.05)
ax21_twin = ax[2, 1].twinx() # instantiate a second axes that shares the same x-axis
sns.boxplot(df, ax = ax21_twin, color = 'r', boxprops=dict(alpha=.3))
#################################################################
dat = np.random.rand(10, 4)
df = pd.DataFrame(dat, columns = ['a', 'b', 'c', 'd'])
wid = 0.25
x_indices = np.arange(len(df['a']))
ax[2, 2].bar(x_indices - 2 * wid, df['a'], width = wid, label = 'a')
ax[2, 2].bar(x_indices - 1 * wid, df['b'], width = wid, label = 'b')
ax[2, 2].bar(x_indices, df['c'], width = wid, label = 'c')
ax[2, 2].bar(x_indices + wid, df['d'], width = wid, label = 'd')
ax[2, 2].legend()
ax[2, 2].set_title('Colorful Bars', fontproperties = fontBlackAdd, fontsize = 30, x = 0.5, y = 1.05)
plt.show()
findfont: Font family ['Fixedsys'] not found. Falling back to DejaVu Sans. findfont: Font family ['Blackadder'] not found. Falling back to DejaVu Sans.
from mpl_toolkits.mplot3d import Axes3D
%matplotlib notebook
fig = plt.figure(figsize = (9, 6))
ax = fig.add_subplot(111, projection = '3d')
x = np.random.randn(100)
y = np.random.randn(100)
z = np.random.randn(100)
ax.scatter(x, y, z, s = 100 * x, c = y)
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('A Wonderful 3D Plot')
ax.set_xlim3d(-1, 3)
ax.set_ylim3d(-1, 3)
ax.set_zlim3d(-1, 3)
(-1.0, 3.0)
%matplotlib notebook
################### Set Font First #############################
import matplotlib.font_manager as font_manager
fontGotham = font_manager.FontProperties(family='Gotham',
weight='bold',
style='normal', size=16)
# the family name can be checked in the property of the font file in 'Control Panel' in Windows OS
fontFixe = font_manager.FontProperties(family='Fixedsys',
weight='bold',
style='normal', size=16)
############################################################################
from mpl_toolkits.mplot3d import Axes3D
############################################################################
fig = plt.figure(figsize = (10,4))
fig.set_facecolor([0.1, 0.1, 0.1])
ax121 = fig.add_subplot(1,2,1, projection='3d')
t = np.arange(0, 10*np.pi, np.pi/50)
xt = np.sin(t)
yt = np.cos(t)
ax121.plot(xt, yt, t)
ax121.set_title('I Am a Spiral', fontproperties = fontFixe,
fontsize = 15, x = 0.5, y = 1.10, color ='w')
ax121.set_facecolor([0.1, 0.1, 0.1])
ax121.grid(True, linestyle='--', linewidth = 10, color = 'red')
ax121.w_xaxis.set_pane_color([0.1, 0.1, 0.1])
ax121.w_yaxis.set_pane_color([0.1, 0.1, 0.1])
ax121.w_zaxis.set_pane_color([0.1, 0.1, 0.1])
ax121.tick_params(axis='x', colors='w') # only affects
ax121.tick_params(axis='y', colors='w') # tick labels
ax121.tick_params(axis='z', colors='w') # not tick marks
#############################################################################
ax122 = fig.add_subplot(1,2,2, projection='3d')
t = np.linspace(0, 4*np.pi, 100)
xt = 10 * np.sin(t) + np.random.randn(100)
yt = 10 * np.cos(t) + np.random.randn(100)
ax122.scatter(xt, yt, t, color = 'red', alpha = 0.5)
ax122.set_title('I Am a Disturbed Scattered Spiral', fontproperties = fontGotham,
fontsize = 15, x = 0.5, y = 1.09, color = 'w')
ax122.w_xaxis.line.set_color('red')
ax122.w_yaxis.line.set_color('red')
ax122.w_zaxis.line.set_color('red')
ax122.tick_params(axis='x', colors='blue') # only affects
ax122.tick_params(axis='y', colors='blue') # tick labels
ax122.tick_params(axis='z', colors='blue') # not tick marks
ax122.xaxis._axinfo['tick']['color']='red'
ax122.yaxis._axinfo['tick']['color']='red'
ax122.zaxis._axinfo['tick']['color']='red'
plt.show()
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from matplotlib import cm
import matplotlib as mpl
%matplotlib notebook
#######################################################################
fontWildOne = font_manager.FontProperties(family='Wild Ones',
weight='bold',
style='normal', size=16)
fontRavie = font_manager.FontProperties(family='RAVIE',
weight='bold',
style='normal', size=16)
########################################################################
fig = plt.figure(figsize = (10,4))
# fig.set_facecolor([0.1, 0.1, 0.1])
ax_121 = fig.add_subplot(1,2,1, projection='3d')
x = np.arange(-8, 8, .5)
y = np.arange(-8, 8, .5)
X,Y = np.meshgrid(x, y)
R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R)/R
ax_121.plot_wireframe(X, Y, Z, linewidth = .5, color = 'k')
ax_121.set_title('This is title $R = \sqrt{X^2 + Y^2} + e$ \n and $Z = \\frac{\sin{R}}{R}$',
fontsize = 12, x = 0.5, y = 1, color = 'k')
ax_121.set_xlabel('X-Axis', fontsize = 10, c = 'r')
ax_121.set_ylabel('Y-Axis', fontsize = 10, c = 'r')
ax_121.set_zlabel('Z-Axis', fontsize = 10, c = 'r')
ax_121.set_xticklabels([]) # get rid of tick labels
ax_121.set_yticklabels([])
ax_121.set_zticklabels([])
#############################################################################
ax_122 = fig.add_subplot(1,2,2, projection='3d')
x = np.arange(-3, 5, .1)
y = np.arange(-3, 5, .1)
X,Y = np.meshgrid(x, y)
R = np.sqrt(np.sin(X) + np.cos(Y))
Z = np.cos(np.sin(R))
ax_122.zaxis.set_major_locator(LinearLocator(3)) # set 13 tickers
ax_122.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) # format is to digits float
surf = ax_122.plot_surface(X, Y, Z,linewidth=0, antialiased=False)
# shrink means shrink the colorbar size, apsect is the ration of width to length
fig.colorbar(surf, shrink =.5 ,aspect = 10)
E:\ANACONDA\lib\site-packages\ipykernel_launcher.py:28: RuntimeWarning: invalid value encountered in true_divide E:\ANACONDA\lib\site-packages\ipykernel_launcher.py:52: RuntimeWarning: invalid value encountered in sqrt E:\ANACONDA\lib\site-packages\ipykernel_launcher.py:57: UserWarning: Z contains NaN values. This may result in rendering artifacts.
<matplotlib.colorbar.Colorbar at 0xbfa5788>
fig = plt.figure(figsize = (10,4))
# fig.set_facecolor([0.1, 0.1, 0.1])
ax121 = fig.add_subplot(1,2,1, projection='3d')
#ax121 = fig.gca(projection='3d')
x = np.arange(-3, 3, 0.25)
y = np.arange(-3, 3, 0.25)
X = np.meshgrid(x, y)[0]
Y = np.meshgrid(x, y)[1]
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
# Plot the surface.
surf = ax121.plot_surface(X, Y, Z, cmap = 'summer')
# Customize the z axis.
ax121.set_zlim(-1.01, 1.01)
ax121.zaxis.set_major_locator(LinearLocator(5))
ax121.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink = 0.5, aspect = 8)
plt.show()
#########################################################################
ax122 = fig.add_subplot(1,2,2, projection='3d')
#ax122.set_aspect('equal')
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = 1 * np.outer(np.cos(u), np.sin(v))
y = 1 * np.outer(np.sin(u), np.sin(v))
z = 1 * np.outer(np.ones(np.size(u)), np.cos(v))
ax122.plot_surface(x, y, z, rstride=4, cstride=4, color='r', linewidth=1.2, alpha = .9)
ax122.set_title('What a fucking Trash!! \n Matplotlib 3D is total trash.',
fontsize = 12, x = 0.5, y = 1, color = 'k')
ax122.set_xlim3d(-1, 1)
ax122.set_ylim3d(-1, 1)
ax122.set_zlim3d(-1, 1)
(-1.0, 1.0)
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
n_radii = 8
n_angles = 36
# Make radii and angles spaces (radius r=0 omitted to eliminate duplication).
radii = np.linspace(0.125, 1.0, n_radii)
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
# Repeat all angles for each radius.
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
# Convert polar (radii, angles) coords to cartesian (x, y) coords.
# (0, 0) is manually added at this stage, so there will be no duplicate
# points in the (x, y) plane.
x = np.append(0, (radii*np.cos(angles)).flatten())
y = np.append(0, (radii*np.sin(angles)).flatten())
# Compute z to make the pringle surface.
z = np.sin(-x*y)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True)
plt.show()
fig = plt.figure(figsize = (10,10))
# fig.set_facecolor([0.1, 0.1, 0.1])
ax121 = fig.add_subplot(2,2,1, projection='3d')
#ax121 = fig.gca(projection='3d')
x = np.arange(-3, 3, 0.25)
y = np.arange(-3, 3, 0.25)
X = np.meshgrid(x, y)[0]
Y = np.meshgrid(x, y)[1]
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
# Plot the surface.
ax121.contour(X, Y, Z, cmap = 'summer')
ax121.set_title('Ordinary Contour')
###################################################################################
ax122 = fig.add_subplot(2,2,2, projection='3d')
ax122.set_title('Filled Contour')
ax122.contourf(X, Y, Z)
######################################################################################
ax123 = fig.add_subplot(2,2,3, projection='3d')
cset = ax123.contour(X, Y, Z, cmap = 'summer', extend3d = True)
ax123.clabel(cset, fontsize=9, inline=1)
####################################################################################
ax124 = fig.add_subplot(2,2,4, projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax124.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
cset = ax124.contour(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm) # zdir means z direction projection, offset means move along the z direction
cset = ax124.contour(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)
cset = ax124.contour(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)
ax124.set_xlabel('X')
ax124.set_xlim(-40, 40)
ax124.set_ylabel('Y')
ax124.set_ylim(-40, 40)
ax124.set_zlabel('Z')
ax124.set_zlim(-100, 100)
(-100, 100)
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
ax.set_title('Filled Contour')
cset = ax.contourf(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)
cset = ax.contourf(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)
cset = ax.contourf(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)
ax.set_xlabel('X')
ax.set_xlim(-40, 40)
ax.set_ylabel('Y')
ax.set_ylim(-40, 40)
ax.set_zlabel('Z')
ax.set_zlim(-100, 100)
plt.show()
t = np.arange(0, 3, 0.1)
s = np.cos(2 * t)
fig, ax = plt.subplots(figsize = (9, 5))
ax.plot(t, s)
ax.axvspan(xmin = .5, xmax = 1.5, facecolor = 'r', alpha = .3)
ax.axhspan(ymin = -.5, ymax = 0, facecolor = 'y', alpha = .3)
ax.annotate('Cross Here!', xy = (1.5, 0), xytext = (1, .5), weight = 'bold', color = 'r',
arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3', color = 'b'))
Text(1, 0.5, 'Cross Here!')
verts = [
(0., 0.), # left, bottom
(0., 1.5), # left, top
(1., .5), # right, top
(.5, 0.), # right, bottom
(0., 0.), # ignored
]
codes = [
mpl.path.Path.MOVETO,
mpl.path.Path.LINETO,
mpl.path.Path.LINETO,
mpl.path.Path.LINETO,
mpl.path.Path.CLOSEPOLY,
]
path = mpl.path.Path(verts, codes)
fig, ax = plt.subplots(figsize = (12, 7))
patch = mpl.patches.PathPatch(path, facecolor='orange', lw=2, alpha = .5)
ax.add_patch(patch)
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
ax.grid()
plt.show()
verts
[(0.0, -0.5), (0.0, 0.5), (0.1, 0.5), (0.1, -0.5), (0.0, -0.5)]
verts = [
(0., -.5), # left, bottom
(0., .5), # left, top
(.1, .5), # right, top
(.1, -.5), # right, bottom
(0., -.5), # ignored
]
codes = [
mpl.path.Path.MOVETO,
mpl.path.Path.LINETO,
mpl.path.Path.LINETO,
mpl.path.Path.LINETO,
mpl.path.Path.CLOSEPOLY,
]
path = mpl.path.Path(verts, codes)
fig, ax = plt.subplots(figsize = (12, 7))
patch = mpl.patches.PathPatch(path, facecolor='red', lw=.1)
ax.add_patch(patch)
ax.plot([.05, .05], [-1.5, 1.2], zorder = 0, lw = 2, color ='k')
ax.set_title('One Candlestick Chart', size = 15)
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
ax.grid()
plt.show()
fig, ax = plt.subplots(figsize = (12, 8))
ax.quiver(0, 0, 2, 2, color = 'red')
ax.grid()
ax.arrow(0, 0, .03, -.03, head_width = .003, head_length= .01, fc = 'r', ec = 'none')
<matplotlib.patches.FancyArrow at 0xc8b8e48>
fig, ax = plt.subplots(figsize = (12, 12))
ax.arrow(0, 0, 2, 2, color = 'red', width = .08,
length_includes_head = True,
head_width = .3, # default: 3*width
head_length = .6,
overhang = .4)
ax.axis([-5, 5, -5, 5])
ax.grid()
soa = np.array([[0, 0, 3, 2], [0, 0, 9, 9]])
X, Y, U, V = zip(*soa)
fig, ax = plt.subplots(figsize = (12, 12))
ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1)
# always use angles = 'xy', scale_units='xy', scale=1, they are a package
# which means to plot vectors in the x-y plane, with u and v having the same units
ax.set_xlim([-1, 10])
ax.set_ylim([-1, 10])
#plt.draw()
ax.grid()
plt.show()
%matplotlib notebook
vec = np.array([[0, 0, 0, 1, 1, 1], [0, 0, 0, -2, 2, 5], [0, 0, 0, 3, -2, 1]])
X, Y, Z, U, V, W = zip(*vec)
fig, ax = plt.subplots(figsize = (9, 9))
ax = fig.gca(projection='3d')
ax.quiver(X, Y, Z, U, V, W, length=1, normalize=False, color = 'red', alpha = .6,arrow_length_ratio = .18, pivot = 'tail',
linestyles = 'solid',linewidths = 3)
ax.grid()
ax.set_xlim([-5, 5])
ax.set_ylim([-5, 5])
ax.set_zlim([-5, 5])
plt.show()
E:\ANACONDA\lib\site-packages\ipykernel_launcher.py:6: UserWarning: Requested projection is different from current axis projection, creating new axis with requested projection.
x_data = []
y_data = []
fig, ax = plt.subplots(figsize = (12, 7))
ax.set_xlim(0,105)
ax.set_ylim(0,12)
line, = ax.plot(0,0)
def animation_frame(i):
x_data.append(i*10)
y_data.append(i)
animation = mpl.animation.FuncAnimation(fig)
fig = plt.figure(figsize=(12,12))
ax = fig.add_subplot(1, 1, 1)
# Major ticks every 20, minor ticks every 5
major_ticks = np.arange(0, 101, 20)
minor_ticks = np.arange(0, 101, 5)
ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)
# And a corresponding grid
ax.grid(which='both')
# Or if you want different settings for the grids:
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.5)
plt.show()
fig, ax = plt.subplots(figsize = (12, 12))
ax.arrow(0, 0, 1, 1, color = 'red', width = .08,
length_includes_head = True,
head_width = .3, # default: 3*width
head_length = .6,
overhang = .4)
ax.arrow(0, 0, -6/5, 1, color = 'blue', width = .08,
length_includes_head = True,
head_width = .3, # default: 3*width
head_length = .6,
overhang = .4)
x = np.arange(-10, 10.6, .5)
y = x
ax.plot(x, y, lw = 2, color = 'red', alpha = .3)
x = np.arange(-10, 10.6, .5)
y = -5/6*x
ax.plot(x, y, lw = 2, color = 'blue', alpha = .3)
###################### Axis, Spines, Ticks ##########################
ax.axis([-10, 10.1, -10.1, 10.1])
ax.spines['left'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('center')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.minorticks_on()
ax.tick_params(axis = 'both', direction = 'inout', length=12, width=2, which='major')
ax.tick_params(axis = 'both', direction = 'inout', length=10, width=1, which='minor')
ax.grid()
plt.axis([-.5, .5, -1.3, .7])
style = 'Simple, tail_width=0.5, head_width=4, head_length=8'
kw = dict(arrowstyle=style, color='k')
a1 = mpl.patches.FancyArrowPatch((-0.4,-0.6), (0,0.6),**kw )
a2 = mpl.patches.FancyArrowPatch((0,0.6), (0.4,-0.6),**kw)
a3 = mpl.patches.FancyArrowPatch((-0.4,-0.6), (0.4,-0.6),connectionstyle='arc3,rad=.5', **kw)
for a in [a1,a2,a3]:
plt.gca().add_patch(a)
plt.show()
fig, ax = plt.subplots(figsize = (12, 12))
ax.axis([-10, 10, -10, 10])
for i in range(100):
style = 'Simple, tail_width=%.3f, head_width=4, head_length=8' % np.random.rand()
kw = dict(arrowstyle=style, color=(np.random.rand(4)))
a = mpl.patches.FancyArrowPatch((0,0), (5*np.random.randn(2)),connectionstyle='arc3,rad=%.3f' %np.random.rand(), **kw)
plt.gca().add_patch(a)
plt.show()
fig, ax = plt.subplots(figsize=(12, 12))
vec = np.array([[0, 0, 4, 2], [0, 0, -2, 2]])
X, Y, U, V = zip(*vec)
ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1, color = 'blue', alpha = .6)
vec2 = np.array([[0,0,2,10]])
X, Y, U, V = zip(*vec2)
ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1, color = 'red', alpha = .6)
vec3 = np.array([[0,0,4,2]])*2
X, Y, U, V = zip(*vec3)
ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1, color = 'blue', alpha = .3)
vec4 = np.array([[0,0,-2,2]])*3
X, Y, U, V = zip(*vec4)
ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1, color = 'blue', alpha = .3)
point1 = [8, 4]
point2 = [2, 10]
line1 = np.array([point1, point2])
ax.plot(line1[:,0], line1[:,1], c = 'b', lw = 3.5,alpha =0.5, ls = '--')
point1 = [-6, 6]
point2 = [2, 10]
line1 = np.array([point1, point2])
ax.plot(line1[:,0], line1[:,1], c = 'b', lw = 3.5,alpha =0.5, ls = '--')
ax.text(vec[0, 2], vec[0, 3], '$u=(4,2)$',size = 20)
ax.text(vec[1, 2] - 2.5, vec[1, 3], '$v=(-1,1)$',size = 20)
ax.text(vec3[0, 2], vec3[0, 3], '$2u$',size = 20)
ax.text(vec4[0, 2]-1, vec4[0, 3], '$3v$',size = 20)
ax.text(2, 10, '$2u+3v$',size = 20)
ax.set_xlim([-10, 10])
ax.set_ylim([0, 10.5])
ax.set_xlabel('x-axis', fontsize =16)
ax.set_ylabel('y-axis', fontsize =16)
ax.grid()
######################################Basis########################################
a = np.arange(-11, 20, 1)
x = np.arange(-11, 20, 1)
for i in a:
y1 = i + .5*x
ax.plot(x, y1, ls = '--', color = 'pink', lw = 2)
y2 = i - x
ax.plot(x, y2, ls = '--', color = 'pink', lw = 2)
ax.set_title('Linear Combination of Two Vectors in $\mathbf{R}^2$', size = 22, x =0.5, y = 1.01)
Text(0.5, 1.01, 'Linear Combination of Two Vectors in $\\mathbf{R}^2$')
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import matplotlib.collections as mcol
arc = mpatches.Arc([.5,.3], .8, .6, theta1=0, theta2=60, angle=20)
col = mcol.PatchCollection(patches=[arc])
col_style = mcol.PatchCollection(patches=[arc], facecolors='none', edgecolors='k')
fig, (ax1,ax2,ax3) = plt.subplots(1,3, figsize=(15,4))
ax1.set_title('add_patch')
ax1.add_patch(arc)
ax2.set_title('add_collection')
ax2.add_collection(col)
ax3.set_title('add_collection, style')
ax3.add_collection(col_style)
plt.show()
x = np.linspace(-4, 4, 100)
y_u = np.sqrt(16 - x**2)
y_d = -np.sqrt(16 - x**2)
fig, ax = plt.subplots(figsize = (8, 8))
ax.plot(x, y_u, color = 'b')
ax.plot(x, y_d, color = 'b')
ax.scatter(0, 0, s = 100, fc = 'k', ec = 'r')
for i in range(len(x)):
ax.arrow(0, 0, x[i], y_u[i], head_width = .18, head_length= .27, length_includes_head = True, width = .03, ec = 'r', fc = 'None')
ax.arrow(0, 0, x[i], y_d[i], head_width = .18, head_length= .27, length_includes_head = True, width = .03, ec = 'r', fc = 'None')
# Define numbers of generated data points and bins per axis.
N_numbers = 100000
N_bins = 100
# set random seed
np.random.seed(0)
# Generate 2D normally distributed numbers.
x, y = np.random.multivariate_normal(
mean=[0.0, 0.0], # mean
cov=[[1.0, 0.4],
[0.4, 0.25]], # covariance matrix
size=N_numbers
).T # transpose to get columns
# Construct 2D histogram from data using the 'plasma' colormap
plt.hist2d(x, y, bins=N_bins, density=False, cmap='plasma')
# Plot a colorbar with label.
cb = plt.colorbar()
cb.set_label('Number of entries')
# Add title and labels to plot.
plt.title('Heatmap of 2D normally distributed data points')
plt.xlabel('x axis')
plt.ylabel('y axis')
# Show the plot.
plt.show()
N_numbers = 100000
N_bins = 20
# set random seed
np.random.seed(0)
# Generate 2D normally distributed numbers.
x, y = np.random.multivariate_normal(
mean=[0.0, 0.0], # mean
cov=[[1.0, 0.4],
[0.4, 0.25]], # covariance matrix
size=N_numbers
).T # transpose to get columns
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
hist, xedges, yedges = np.histogram2d(x, y, bins=N_bins)
# Add title and labels to plot.
plt.title('3D histogram of 2D normally distributed data points')
plt.xlabel('x axis')
plt.ylabel('y axis')
# Construct arrays for the anchor positions of the bars.
# Note: np.meshgrid gives arrays in (ny, nx) so we use 'F' to flatten xpos,
# ypos in column-major order. For numpy >= 1.7, we could instead call meshgrid
# with indexing='ij'.
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25)
xpos = xpos.flatten('F')
ypos = ypos.flatten('F')
zpos = np.zeros_like(xpos)
# Construct arrays with the dimensions for the 16 bars.
dx = 0.5 * np.ones_like(zpos)
dy = dx.copy()
dz = hist.flatten()
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')
# Show the plot.
plt.show()
fig, axs = plt.subplots(figsize = (5, 5))
N_numbers = 100000
N_bins = 100
k = 1000000
mu1, mu2 = 0, 0
sigma1, sigma2 = 2, 5
mu = np.array([mu1, mu2])
Sigma = np.array([[sigma1, 0], [0, sigma2]])
mn = sp.stats.multivariate_normal(mean=mu, cov=Sigma)
X = mn.rvs(size=k)
axs.hist2d(X[:,0], X[:,1], bins=N_bins, density=False, cmap='plasma')
axs.set_title('Heatmap of 2D Bivariate Random Draws')
axs.set_xlabel('x axis')
axs.set_ylabel('y axis')
axs.axis('equal')
plt.show()