下面的练习题都是在Jupyter上进行,如果想知道如何创建一个Jupyter Notebooks, 请看这里
下面就开始代码环节:(题目跟答案都会一同显示)
第一题:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,100)
y = x*2
z = x**2
# Exercise 1
# Create a figure object called fig using plt.figure()
# Use add_axes to add an axis to the figure canvas at [0,0,1,1]. Call this new axis ax.
# Plot(x,y) on that axes and set the labels and titles:
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.plot(x,y)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('title')
plt.show()
结果如下:
第二题:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,100)
y = x*2
z = x**2
# Exercise 2
# Create a figure object and put two axes on it, ax1 and ax2. Located at [0,0,1,1] and [0.2,0.5,.2,.2] respectively
# Plot(x,y) on both axes. And call your figure object to show it
fig = plt.figure()
ax1 = fig.add_axes([0,0,1,1])
ax2 = fig.add_axes([0.2,0.5,.2,.2])
ax1.plot(x,y,'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('Big')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('Small')
ax2.plot(x,y)
plt.show()
结果如下:
第三题:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,100)
y = x*2
z = x**2
# Exercise 3
# Create the plot by adding two axes to a figure object at [0,0,1,1] and [0.2,0.5,.4,.4]
# Use x,y, and z arrays to recreate the plot. Notice the x limits and y limits on the inserted plot
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax2 = fig.add_axes([0.2,0.5,.4,.4])
ax.plot(x,z)
ax.set_xlabel('X')
ax.set_ylabel('Z')
ax2.plot(x,y)
ax2.set_title('zoom')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_xlim([20,22])
ax2.set_ylim([30,50])
plt.show()
结果如下:
第四题:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,100)
y = x*2
z = x**2
# Exercise 4
# Use plt.subplots(nrows=1,ncols=2) to create the plot
# plot(x,y) and (x,z) on the axes. Play aroung with the linewidth and style
# See if you can resize the plot by adding the figsize() argument in plt.subplots()
# axes = plt.subplots(nrows=1,ncols=2, figsize=(12,2)) # figsize=(width_img, height_img) 这种写法是错的,“AttributeError: 'Figure' object has no attribute 'plot'”
fig,axes = plt.subplots(nrows=1,ncols=2, figsize=(12,2)) # figsize=(width_img, height_img)
axes[0].plot(x,y,'g')
axes[1].plot(x,z,'r')
plt.show()
结果如下:
下面,博主额外提供一些料,设想这种情况:如果有很多subplots,应该采用什么方法能迅速将数据填入到图表里?
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,100)
y = x*2
fig,axes = plt.subplots(nrows=2,ncols=3)
for row in axes:
for col in row:
col.plot(x,y)
plt.tight_layout()
plt.show()
结果如下:
使用这种方法能,不管有多少子图,都能迅速将数据填入到表中。
如果觉得不错,就点赞或者关注或者留言~~
谢谢~ ~