Import required libraries

import matplotlib.pyplot as plt
import numpy as np
from jupyterthemes import jtplot
jtplot.style(grid=False)


Establish xy correspondence

x = np.linspace(-2, np.pi)
y1 = np.sin(x)
y2 = np.cos(x)


plot()

matplotlib. pyplot. Detailed explanation of plot () parameters
https://matplotlib.org/api/pyplot_summary.html

#Single line:
plot([x], y, [fmt], data=None, **kwargs)
#Draw multiple lines together
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)

plt.figure(num=2,figsize=(8,5))
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.show()


plt.xlim(), plt.ylim()

Determines the xy range displayed

plt.figure(num=2,figsize=(8,5))
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('I am x')
plt.ylabel('I am y')
plt.savefig("1.png")
plt.show()


Modify the labels of X and Y axes

new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.22,3],[r' n n n',r' n r nr nr',r' s s s',r' s r sr sr',r' s s r ssr ssr'])

plt.figure(num=3,figsize=(8,5))
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('I am x')
plt.ylabel('I am y')
new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.22,3],[r'$n$',r'$nr$',r'$s$',r'$sr$',r'$ssr$'])
plt.show()


Modify border

ax = plt.gca()
ax.spines ['the edge you want to modify'] set_color(‘none’)

Modify axis position

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

plt.figure(num=3,figsize=(8,5))
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('I am x')
plt.ylabel('I am y')
new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.22,3],[r'$n$',r'$nr$',r'$s$',r'$sr$',r'$ssr$'])

ax = plt.gca()
ax.spines['right'].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))

plt.show()


Little practice

import matplotlib.pyplot as plt
import numpy as np

from jupyterthemes import jtplot
jtplot.style(grid=False)

#Set style
plt.style.use(plt.style.available[1])

#Display Chinese
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']

#Used to display negative signs normally
plt.rcParams['axes.unicode_minus']=False

x = np.linspace(-2, 3)
y = x-1

#Draw a line. Label is the label of the line
plt.plot(x,y,color='blue',linewidth=1.0,linestyle='--',label='y=x-1')

plt.xlim((-1,2))
plt.ylim((-2,1))
plt.xlabel('X')
plt.ylabel('Y')
new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
plt.yticks([-1,-0.5,1],[r'$bad$',r'$normal$',r'$good$'])

ax = plt.gca()
ax.spines['right'].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))

plt.title(r'Data visualization exercises')

#Add a legend to show the corresponding relationship between label and
plt.legend(loc='best',edgecolor='green')

#Save picture
plt.savefig("Data visualization.png")

plt.show()


Annotation annotation

When some special places in the drawing line need to be marked, we can use annotation There are two methods for annotation in Matplotlib: one is to use the annotate in plt, and the other is to write annotations directly with text in plt. First, review the drawing tutorial in the previous chapter:

x = np.linspace(-3, 3, 50)
y = 2*x + 1

plt.figure(num=1, figsize=(8, 5),)
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))
plt.plot(x, y,)

x0 = 1
y0 = 2*x0 + 1
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
# set dot styles
plt.scatter([x0, ], [y0, ], s=50, color='b')

<matplotlib.collections.PathCollection at 0x1bf13d48ac8>


Next, we label the point (x0, y0). The first way is to use the function annotate(), where r ''% y0 represents the content of the annotation. You can pass the value of y0 into the string through the string% s; The parameter xycoords = 'data' means that the position is selected based on the value of the data. xytext=(+30, -30) and textcoords = 'offset points' represent the description and xy deviation value of the annotation position, that is, the annotation position is the xy position moving 30 to the right and 30 to the down. Arrowprops is the setting of the arrow type and arrow radian in the figure, which needs to be passed in in the form of dict.

plt.figure(num=1, figsize=(8, 5),)
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))
plt.plot(x, y,)

x0 = 1
y0 = 2*x0 + 1
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
# set dot styles
plt.scatter([x0, ], [y0, ], s=50, color='b')
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
textcoords='offset points', fontsize=16,

Text(30,-30,'$2x+1=3$')


The second annotation method is through the text() function

plt.figure(num=1, figsize=(8, 5),)
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))
plt.plot(x, y,)

x0 = 1
y0 = 2*x0 + 1
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
# set dot styles
plt.scatter([x0, ], [y0, ], s=50, color='b')
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
textcoords='offset points', fontsize=16,
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
fontdict={'size': 16, 'color': 'r'})

Text(-3.7,3,'$This\\ is\\ the\\ some\\ text. \\mu\\ \\sigma_i\\ \\alpha_t$')


plt.figure(num=3,figsize=(8,5))
plt.plot(x,y2,label='cos x')
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--',label='sin x')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('I am x')
plt.ylabel('I am y')
new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.22,3],[r'$n$',r'$nr$',r'$s$',r'$sr$',r'$ssr$'])

ax = plt.gca()
ax.spines['right'].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))

plt.legend(loc='best',edgecolor='brown')

plt.show()


plt.subplot(2,1,1)
plt.plot([0,1],[0,1])

plt.subplot(2,3,4)
plt.plot([0,1],[0,1])

plt.subplot(2,3,5)
plt.plot([0,1],[0,1])

plt.subplot(2,3,6)
plt.plot([0,1],[0,1])

[<matplotlib.lines.Line2D at 0x223d1011748>]


ax1 = plt.subplot2grid((3,3),(0,0),colspan=3)
ax1.plot([1,2],[1,2])
ax1.set_title('ax1_title')

ax2 = plt.subplot2grid((3,3),(1,0),colspan=2)

ax3 = plt.subplot2grid((3,3),(1,2),rowspan=3)

ax4 = plt.subplot2grid((3,3),(2,0))

ax5 = plt.subplot2grid((3,3),(2,1))

ax4.scatter([1,2],[2,2])
ax4.set_xlabel('ax4_x')
ax4.set_ylabel('ax4_y')

Text(0,0.5,'ax4_y')


f,((ax11,ax12),(ax13,ax14)) = plt.subplots(2,2,sharex=True,sharey=True)
ax11.scatter([1,2], [1,2])

<matplotlib.collections.PathCollection at 0x20fe72b4358>


Use the same tick mark

The twinx() function represents the shared x-axis
twiny() indicates the shared y-axis
Sharing means that the x axis uses the same tick mark

python -- twinx() function in suplot
ax2 = ax1.twinx()

fig,ax1 = plt.subplots()

ax2 = ax1.twinx()

ax1.plot(x,y1,'g-')
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.plot(x, y2, 'b-') # blue
ax2.set_ylabel('Y2 data', color='b')

practice

Method 1 PLT subplot

#Set style
plt.style.use(plt.style.available[0])

#Display Chinese
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']

#Used to display negative signs normally
plt.rcParams['axes.unicode_minus']=False

plt.figure(figsize=(6,6))

plt.suptitle('practice ')

x = np.linspace(-3, 3)
y = x

plt.subplot(2,2,1)
plt.plot(x,y,label='y = x',color='grey')
plt.legend(loc='best',edgecolor='brown')

y = x**2

plt.subplot(2,2,2)
plt.plot(x,y,label='y = x^2',color='b')
plt.legend(loc='best',edgecolor='brown')

y = 0.01*x - 0.01

plt.subplot(2,1,2)
plt.plot(x,y,label='y=0.01*x-0.01',color='r')
plt.legend(loc='best',edgecolor='brown')


<matplotlib.legend.Legend at 0x1bf0f1b41d0>


Method 2 PLT subplots

#Set style
plt.style.use(plt.style.available[21])

#Display Chinese
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']

#Used to display negative signs normally
plt.rcParams['axes.unicode_minus']=False

f, ((ax11, ax12), (ax13, ax14)) = plt.subplots(2, 2, sharex=False, sharey=False,figsize=(6, 6))

plt.suptitle('practice ')

x = np.linspace(-3, 3)
y = x

ax11.plot(x,y,label='y = x',color='grey')
ax11.legend(loc='best',edgecolor='brown')

y = x**2

ax12.plot(x,y,label='y = x^2',color='b')
ax12.legend(loc='best',edgecolor='brown')

y = 0.01*x - 0.01

plt.subplot(2,1,2)
plt.plot(x,y,label='y=0.01*x-0.01',color='r')
plt.legend(loc='best',edgecolor='brown')

<matplotlib.legend.Legend at 0x1bf13c57908>


Method 3 PLT subplot2grid

#Set style
plt.style.use(plt.style.available[11])

#Display Chinese
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']

#Used to display negative signs normally
plt.rcParams['axes.unicode_minus']=False

plt.figure(figsize=(6, 6))

plt.suptitle('practice ')

x = np.linspace(-3, 3)
y = x

ax1 = plt.subplot2grid((2,2),(0,0),colspan=1)
ax1.plot(x,y,label='y = x',color='grey')
ax1.legend(loc='best',edgecolor='brown')

y = x**2
ax2 = plt.subplot2grid((2,2),(0,1),colspan=1)
ax2.plot(x,y,label='y = x^2',color='b')
ax2.legend(loc='best',edgecolor='brown')

y = 0.01*x - 0.01

ax2 = plt.subplot2grid((2,2),(1,0),colspan=2)
ax2.plot(x,y,label='y=0.01*x-0.01',color='r')
ax2.legend(loc='best',edgecolor='brown')

<matplotlib.legend.Legend at 0x1bf11fdfd68>


Posted by thallium6 on Sat, 14 May 2022 06:49:55 +0300