折线图

image.png

1
2
3
4
5
6
7
8
9
10
11
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=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
plt.tick_params(axis='both', labelsize=14)
plt.show()
  • plt.plot(input_value, squares, linewidth=5) 绘制折线图
    • input_value x轴数据
    • squares y轴数据
    • linestyle 线条种类
    • linewidth 线条粗细
    • color 线条颜色
  • plt.title() 设置标题
    • fontsize 字体大小
    • fontstyle 字体样式
      • normal 默认
      • italic 斜体
      • oblique 倾斜
    • fontweight 字体粗细
      • normal 默认
      • light 细
      • bold 粗
    • color 字体颜色
    • fontfamily 字体家族
      • serif 有衬线体(像宋体)
      • sans-serif 无衬线体(像黑体)
      • cursive 花体字(新奇美观一点)
  • plt.xlabel() 设置横坐标标签
  • plt.ylabel() 设置纵坐标标签
  • plt.tick_params(axis= ,labelsize=) 设置横纵坐标刻度大小
    • axis 指定轴
      • ‘x’
      • ‘y’
      • ‘both’ 默认
    • which 刻度类型
      • major 主刻度 默认
      • minor 次刻度
      • both 全部
    • direction 刻度方向 in out inout
    • width 刻度宽度
    • length 刻度长度
  • plt.grid(True) 添加网线格

散点图

image.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import matplotlib.pyplot as plt 

x_values = list(range(1,1001))
y_values = [x**2 for x in x_values]

plt.scatter(x_values, y_values, c = y_values, cmap=plt.cm.Blues, edgecolor='none', s=10)

plt.title("Square Numbers", fontsize=24, fontfamily='cursive')
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
plt.tick_params(axis='both', which='both',labelsize=14, direction='inout')
plt.axis([0, 1100, 0, 1100000])

plt.show()
  • plt.scatter
    • c 指定散点颜色(如果设置颜色映射可以设为 y 值)
    • s 指定散点大小
    • cmap 颜色映射 cmap=plt.cm.Blues 蓝色渐变
    1. Sequential: 渐变色映射,通常用于表示有序数据,颜色从浅到深或从深到浅。
      • 'viridis''plasma''inferno''magma''cividis'
      • 'Greys''Purples''Blues''Greens''Oranges''Reds'
      • 'YlOrBr''YlOrRd''OrRd''PuRd''RdPu''BuPu'
      • 'GnBu''PuBu''YlGnBu''PuBuGn''BuGn''YlGn'
    2. Diverging: 发散色映射,通常用于表示具有明显中间值(如零)的数据,颜色从中间向两端发散。
      • 'PiYG''PRGn''BrBG''PuOr''RdGy''RdBu'
      • 'RdYlBu''RdYlGn''Spectral''coolwarm''bwr''seismic'
    3. Cyclic: 循环色映射,通常用于表示周期性数据,颜色在两端循环。
      • 'twilight''twilight_shifted''hsv'
    4. Qualitative: 定性色映射,通常用于表示分类数据,颜色之间没有顺序关系。
      • 'Pastel1''Pastel2''Paired''Accent'
      • 'Dark2''Set1''Set2''Set3'
      • 'tab10''tab20''tab20b''tab20c'
    5. Miscellaneous: 其他类型的色映射。
      • 'flag''prism''ocean''gist_earth''terrain''gist_stern'
      • 'gnuplot''gnuplot2''CMRmap''cubehelix''brg''gist_rainbow'
      • 'rainbow''jet''nipy_spectral''gist_ncar'
  • plt.axis([0, 1100, 0, 1100000]) 指定坐标轴范围,接收列表参数
  • plt.savefig('squares_plot.png', bbox_inches='tight') 保存为图片
    • 前一个指定图片名称
    • 后一个指定将图表多余的空白区域裁剪掉
      • tight 自动调整边界框,确保内容完整
      • standard 使用默认的边界框,可能会导致部分内容被裁剪
      • None 使用当前的边界框设置

随机漫步

image.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from random import choice
import matplotlib.pyplot as plt

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:
# 决定前进方向以及沿这个方向前进的距离
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值,始终提取最新的位置
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(50000)
rw.fill_walk()
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, s = 1, c = point_numbers, cmap="Blues", edgecolors='none')

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.axis("off")
plt.figure(dpi=2000, figsize=(10, 6))

plt.show()
  • plt.figure(dpi=, figsize=)
    • dpi 分辨率
    • figsize 窗口尺寸
  • plt.axis("off") 隐藏所有的坐标轴

直方图

image.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import pygal
from IPython.display import SVG
from random import randint

class Die():
"""表示一个骰子的类"""

def __init__(self, num_sides=6):
"""骰子默认为6面"""
self.num_sides = num_sides

def roll(self):
"""返回一个位于1和骰子面数之间的随机值"""
return randint(1, self.num_sides)

# 创建两个D6骰子
die_1 = Die()
die_2 = Die()
die_3 = Die()

# 掷骰子多次,并将结果存储到一个列表中
results = [die_1.roll() + die_2.roll() + die_3.roll() for roll_num in range(1000)]

# 分析结果
max_result = die_1.num_sides + die_2.num_sides + die_3.num_sides
frequencies = [results.count(value) for value in range(3, max_result+1)]

hist = pygal.Bar()

hist.title = "Results of rolling three D6 1000 times."
hist.x_labels = [str(x) for x in range(3, 19)]
hist.x_title = "Result"
hist.y_title = "Frequency of Result"

hist.add('D6+D6+D6', frequencies)

# 保存图表为 SVG 文件
hist.render_to_file("die_visual.svg")

# 在 Jupyter Notebook 中显示 SVG 文件
SVG("die_visual.svg")
  • pygal.Bar() 生成条形图
    • title 设置标题
    • x_labels 设置x轴刻度
    • x_title 设置x轴标题
    • y_title 设置y轴标题
  • .add(title, values)
    • title 图例数据的名称
    • values 数据的值(通常是列表)
  • IPython.display.SVG() IPython(Jupyter Notebook)中用于在笔记本中直接显示 SVG 图像的工具