Python matplotlib折线图,散点图的绘制

it2026-08-26  3

简单折线图绘制

#!/usr/bin/env python3 # -*- coding:utf-8 -*- import matplotlib.pyplot as plt input_value = [1, 2, 3, 4, 5] squares = [1, 4, 9, 16, 25] # 绘制点并且用线连接起来 plt.plot(input_value, squares, linewidth=5) # 设置标题, 以及给坐标轴加上标签 plt.title("Square Numbers", fontsize=14) plt.xlabel("Value", fontsize=14) plt.ylabel("Square of Value", fontsize=14) # 设置刻度标记大小 plt.tick_params(axis="both", labelsize=14) # 显示 plt.show()

简单散点图绘制

少量数据的散点图

#!/usr/bin/env python3 # -*- coding:utf-8 -*- import matplotlib.pyplot as plt x_value = [1, 2, 3, 4, 5] y_value = [1, 4, 9, 16, 25] plt.scatter(x_value, y_value, s=200) # 设置标题, 以及给坐标轴加上标签 plt.title("Square Numbers", fontsize=14) plt.xlabel("Value", fontsize=14) plt.ylabel("Square of Value", fontsize=14) # 设置刻度标记大小 plt.tick_params(axis="both", which="major", labelsize=14) # 显示 plt.show()

大量数据的散点图

#!/usr/bin/env python3 # -*- coding:utf-8 -*- import matplotlib.pyplot as plt x_value = [i for i in range(1000)] y_value = [i * i for i in x_value] # edgecolors="none" 删除数据点的轮廓 # c: 设置颜色 plt.scatter(x_value, y_value, c='red', edgecolors="none", s=20) # 设置标题, 以及给坐标轴加上标签 plt.title("Square Numbers", fontsize=14) plt.xlabel("Value", fontsize=14) plt.ylabel("Square of Value", fontsize=14) # 设置每个坐标轴的取值范围 plt.axis([0, 1100, 0, 1100000]) # 保存图表 # bbox_inches="tight" : 裁剪掉多余的空白区域 plt.savefig("scatter_plot.png", bbox_inches="tight") # 显示 plt.show()

随机漫步

#!/usr/bin/env python3 # -*- coding:utf-8 -*- from random import choice import matplotlib.pyplot as plt class RandomWalk(object): def __init__(self, num_points=5000): self.num_points = num_points self.x_values = [0] self.y_values = [0] def fill_walk(self): while len(self.x_values) < self.num_points: 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 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) rw = RandomWalk() rw.fill_walk() plt.scatter(rw.x_values, rw.y_values, s=10) plt.show()
最新回复(0)