matplotlib官网地址:http://matplotlib.org/
使用pyplot绘制简单的折线图
import matplotlib.pyplot as plt
input_values = [1,2,3,4,5]
squares = [1,4,9,16,25]
#设置绘制线条的粗细
plt.plot(input_values,squares,linewidth = 5)
#设置图表标题并给坐标轴加上标签
plt.title("Square Numbers",fontsize = 24)
plt.xlabel("Value",fontsize = 17)
plt.ylabel("Square of value",fontsize = 17)
#设置刻度标记的大小
plt.tick_params(axis = "both",labelsize = 20)
plt.show()
使用pyplot绘制散点图
import matplotlib.pyplot as plt
x_values = list(range(1,1001))
y_values = [x**2 for x in x_values]
#s设置点的尺寸 点颜色 轮廓颜色 c 设置点的颜色 cmap 设置颜色映射 edgecolor 轮廓 s 点的尺寸
plt.scatter(x_values,y_values,c = y_values,cmap = plt.cm.Reds,edgecolor = 'none',s = 2)
#设置标题以及给坐标轴加上标签
plt.title("Square Numbers",fontsize = 24)
plt.xlabel("Value",fontsize = 17)
plt.ylabel("Square of value",fontsize = 17)
#设置标记刻度的大小
plt.tick_params(axis = "both",which = "major",labelsize = 14)
#设置每个坐标轴的取值范围
plt.axis([0,1100,0,1100000])
#保存图片,并将图片多余的空白部分裁剪掉
plt.savefig("squares_plot.png",bbox_inches = "tight")
附,随机漫步图形的制作
- 创建RandomWalk类
from random import choice class RandomWalk(): """一个生成随机漫步数据的类""" def __init__(self,num_points = 5000): """初始化随机漫步的属性""" #随机漫步点的个数 self.num_points = num_points #所有随机漫步都始于(0,0) self.x_values = [0] self.y_values = [0] def fill_walk(self): """计算随机漫步包含的所有点""" #不断漫步,直到列表达到指定的长度 while len(self.x_values) < self.num_points: #决定前进方向以及沿这方向前进的距离 #函数choice 参数当中的列表中选择一个元素 x_direction = choice([1,-1]) x_distance = choice([0,1,2,3,4]) #最终漫步将有方向和步数决定 x_step = x_direction * x_distance y_direction = choice([1,-1]) y_distance = choice([0,1,2,3,4]) y_step = y_direction * y_distance #拒绝原地踏步 if x_step == 0 and y_step == 0: continue #计算下一个点的x和y值 索引-1表示列表倒数第一个值 next_x = self.x_values[-1] + x_step next_y = self.y_values[-1] + y_step #将坐标添加进列表 self.x_values.append(next_x) self.y_values.append(next_y)
- 绘制随机漫步图形
import matplotlib.pyplot as plt from random_walk import RandomWalk from time import sleep #生成50000个随机漫步点 rw = RandomWalk(50000) rw.fill_walk() #设置绘图窗口的尺寸 单位为尺寸 如下铺满整个屏幕 plt.figure(figsize = (16,9)) #一个从1到50000的列表 point_numbers = list(range(rw.num_points)) #画图 plt.scatter(rw.x_values,rw.y_values,c = point_numbers,cmap = plt.cm.Reds,edgecolors = 'none',s = 1) #突出起点和终点 重绘 plt.scatter(0,0,c = "green",edgecolors = 'none',s = 100) plt.scatter(rw.x_values[-1],rw.y_values[-1],c = 'red',edgecolors = 'none',s = 100) #隐藏坐标轴 plt.axes().get_xaxis().set_visible(False) plt.axes().get_yaxis().set_visible(False) plt.savefig("random_walk.png")