Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.
plot
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 1000)
y = np.sin(x)
z = np.cos(x**2)
plt.figure(figsize=(8,4))
plt.plot(x,y,label="$sin(x)$",color="red",linewidth=2)
plt.plot(x,z,"b--",label="$cos(x^2)$")
plt.xlabel("Time(s)")
plt.ylabel("Volt")
plt.title("PyPlot First Example")
plt.ylim(-1.2,1.2)
plt.legend()
plt.show()
'''
xlabel: Set the text of the X axis
ylabel: set the Y axis text
title: Set the title of the chart
ylim: set the Y axis range
legend: show icon
'''
result:
subplot(numRows, numCols, plotNum) to draw multi-axis plots
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 1000)
y = np.sin(x)
z = np.cos(x**2)
t = np.tanh(x)
plt.figure(figsize=(8,4))
plt.subplot(221) # Left image of the first line
plt.title("sin(x)")
plt.plot(x,y,label="$sin(x)$",color="red",linewidth=2)
plt.legend()
plt.subplot(222) # Right image of the first line
plt.title("cos(x^2)")
plt.plot(x,z,"b--",label="$cos(x^2)$")
# plt.legend() #Untitled after comment
plt.subplot(212) # second full line
plt.title("tanh(x)")
plt.plot(x,t,label="$tanh(x)$",color="blue",linewidth=1)
plt.legend()
plt.show()
Annotate the content on the picture
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y = 2*x + 1
plt.figure(num=1, figsize=(8, 5),)
plt.plot(x, y,)
#Set border line
ax = plt.gca()
#Set the right and top borders to none
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
#Set the left and bottom borders to the origin
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
#Draw a point
x0 = 1
y0 = 2*x0 + 1
plt.plot([x0, x0,], [0, y0,],'k--', linewidth=2.5)#k--black dotted line
#scatter dotted line, s control point size
plt.scatter([x0, ], [y0, ], s=50, color='b')
#Set an annotated arrow, $$ symbol to set the font, xy, xycoords, xytext to set the position,
plt.annotate(r'$2x+1=%s$'% y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
textcoords='offset points',#set line shape
fontsize=16,
arrowprops=dict(arrowstyle='->', #set arrow format
connectionstyle="arc3,rad=.2") )#Set the bending degree of the line
#Set a comment
plt.text(-3, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',#\ is used as an escape character
fontdict={'size': 16,'color':'r'})
plt.show()
Set the size and background of the scale numbers on the coordinate axis
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y = 0.1*x
plt.figure()
plt.plot(x, y, linewidth=10, zorder=1) # set zorder for ordering the plot in plt 2.0.2 or higher
plt.ylim(-2, 2)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
#Set the size and background of the scale numbers on the coordinate axis to prevent being blocked by thick lines
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12)
# set zorder for ordering the plot in plt 2.0.2 or higher
label.set_bbox(dict(facecolor='white', edgecolor='none', alpha=0.8,zorder=2 ))# Font background is white, border is none, alpha represents transparency 0.8
plt.show()
Draw a scatterplot
import matplotlib.pyplot as plt
import numpy as np
n = 1024 # data size
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
T = np.arctan2(Y, X) # for color later on
plt.scatter(X, Y, s=75, c=T, alpha=.5)
plt.xlim(-1.5, 1.5)
plt.xticks(()) # ignore xticks
plt.ylim(-1.5, 1.5)
plt.yticks(()) # ignore yticks
plt.show()
Draw a histogram
import matplotlib.pyplot as plt
import numpy as np
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)
#Draw columnarity
plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')#Forward, the color of facecolor cylinder, edgecolor border color
plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')#negative
#Set the digital annotation at the top of the histogram
for x, y in zip(X, Y1):
# ha: horizontal alignment
# va: vertical alignment
plt.text(x + 0.4, y + 0.05,'%.2f'% y, ha='center', va='bottom')
for x, y in zip(X, Y2):
# ha: horizontal alignment
# va: vertical alignment
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.show()