在进入本门课内容之前有的同学反映在使用pythonanywhere时程序偶尔会莫名其妙的报错,遇到这种情况的处理办法是先kill当前的控制台进程(见下图),然后重新run一下自己的python文档,一般就可以恢复正常。
下面是一个利用matplotlib进行画图的例子,以下的例子都在pythonanywhere里面亲测可用:
1 from matplotlib import pyplot as plt 2 import numpy as np 3 x = np.linspace(0, 10, 20) 4 y = x * x + 2 5 fig = plt.figure() 6 axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) 7 axes.plot(x, y, 'r') 8 fig.savefig("hay.png")
在上面这个例子中plt.figure()相当于定义了一个木头画板,fig.add_axes函数相当于定义了一个帆布画布,0.1,0.1是画布的右上角相对于画板的右上角的偏移量(最大值是1),0.8和0.8相当于画布自身的宽和高(最大值是1)。axes.plot相当于在画布里面画图。最终画图的结果hay.png存储在File目录下,可以下载查看。linspace(0,10,20)的含义是在0到10之间生成等间距的20个数字。
我们可以在上面的代码中加入axes.set_title("Beautiful Map")这句话来设置绘图的标题:
我们可以通过axes.set_xlabel("USA")和axes.set_ylabel("UK")这两句话来为横纵坐标轴起名字。
下面的代码通过axes.legend来为绘图添加图例:
1 from matplotlib import pyplot as plt 2 import numpy as np 3 x = np.linspace(0, 10, 20) 4 fig, axes = plt.subplots() 5 6 axes.set_xlabel('x label') 7 axes.set_ylabel('y label') 8 axes.set_title('title') 9 10 axes.plot(x, x**2) 11 axes.plot(x, x**3) 12 axes.legend(["y = x**2", "y = x**3"], loc=2) 15 fig.savefig("hay.png")
loc参数
1
, 2
, 3
and 4
分别代表图例的位置: 右上, 左上, 左下 and 右下。
下面是一个在一张画布里布局多个子图的例子,第五行的subplots函数接受两个参数,第一个参数是画布的行数,第二个参数是画布的列数,在这里是一行两列,每列画一个子图:
1 from matplotlib import pyplot as plt 2 import numpy as np 3 x = np.linspace(0, 10, 20) 4 y = x * x + 2 5 fig, axes = plt.subplots(nrows=1, ncols=2) # Submap is of 1 row, 2 columns 6 for ax in axes: 7 ax.plot(x, y, 'r') 8 fig.savefig("hay.png")
我们可以在一个大的画布里面再嵌套一个小的画布,具体例子如下所示:
1 from matplotlib import pyplot as plt 2 import numpy as np 3 x = np.linspace(0, 10, 20) 4 y = x * x + 2 5 fig = plt.figure() # New drawing board 6 7 axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # Big canvas 8 axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # Small canvas 9 10 # Big drawing board 11 axes1.plot(x, y, 'r') 12 13 # Small drawing board 14 axes2.plot(y, x, 'g') 15 fig.savefig("hay.png")
下面的代码中:第五行的figsize指定了画板的宽度和高度。第八行的lw代表线的粗细,第九行的grid(true)给绘图添加了网格线,第十三和第十四行的set_ylim和set_xlim指定了坐标轴的取值范围。
1 from matplotlib import pyplot as plt 2 import numpy as np 3 4 x = np.linspace(0, 10, 20) 5 fig, Axes = plt.subplots(1, 2, figsize=(10,5)) 6 7 # Display the grid 8 Axes[0].plot(x, x**2, x, x**3, lw=5) 9 Axes[0].grid(True) 10 11 # Set the axis range 12 Axes[1].plot(x, x**2, x, x**3) 13 Axes[1].set_ylim([0, 60]) 14 Axes[1].set_xlim([2, 5]) 15 16 fig.savefig("hay.png")