第 15 章 生成数据
软件准备
- 安装Matplotlib
- 安装ploty
pip install matplotlib
pip install plotly
15.2 绘制简单的折线图
mpl_squares.py
import matplotlib.pyplot as plt
squares = [1,4,9,16,25]
# 变量fig 表示整张图片,变量ax表示图片中的各个图表
fig, ax = plt.subplots()
ax.plot(squares)
# 打开Matplotlib查看器并显示绘制的图表
plt.show()
运行结果:
15.2.1 修改标签文字和线条粗细
import matplotlib.pyplot as plt
squares = [1,4,9,16,25]
# 变量fig 表示整张图片,变量ax表示图片中的各个图表
fig, ax = plt.subplots()
ax.plot(squares,linewidth=3)
# 设置图表标题并给坐标轴加上标签
ax.set_title("平方数",fontsize=24)
ax.set_xlabel("值",fontsize=14)
ax.set_ylabel("值的平方",fontsize=14)
# 设置刻度标记的大小
ax.tick_params(axis='both',labelsize=14)
# 打开Matplotlib查看器并显示绘制的图表
plt.show()
运行结果:
15.2.2 校正图形
import matplotlib.pyplot as plt
input_values = [1,2,3,4,5]
squares = [1,4,9,16,25]
# 变量fig 表示整张图片,变量ax表示图片中的各个图表
fig, ax = plt.subplots()
ax.plot(input_values,squares,linewidth=3)
# 设置图表标题并给坐标轴加上标签
ax.set_title("平方数",fontsize=24)
ax.set_xlabel("值",fontsize=14)
ax.set_ylabel("值的平方",fontsize=14)
# 设置刻度标记的大小
ax.tick_params(axis='both',labelsize=14)
# 打开Matplotlib查看器并显示绘制的图表
plt.show()
运行结果:
15.2.3 使用内置样式
import matplotlib.pyplot as plt
input_values = [1,2,3,4,5]
squares = [1,4,9,16,25]
# 变量fig 表示整张图片,变量ax表示图片中的各个图表
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(input_values,squares,linewidth=3)
# 设置图表标题并给坐标轴加上标签
ax.set_title("平方数",fontsize=24)
ax.set_xlabel("值",fontsize=14)
ax.set_ylabel("值的平方",fontsize=14)
# 设置刻度标记的大小
ax.tick_params(axis='both',labelsize=14)
# 打开Matplotlib查看器并显示绘制的图表
plt.show()
运行结果:
15.2.4 使用scatter() 绘制散点图并设置样式
catter_squares.py
import matplotlib.pyplot as plt
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.scatter(2,4,s=200) # 加上标签,并确保所有文本都达到能够看清
# 设置图表标题并给坐标轴加上标签
ax.set_title("平方数",fontsize=24)
ax.set_xlabel("值",fontsize=14)
ax.set_ylabel("值的平方",fontsize=14)
# 设置刻度标记的大小
ax.tick_params(axis='both',which='major',labelsize=14)
plt.show()
运行结果:
15.2.5 使用scatter() 绘制一系列点
scatter_squares.py
import matplotlib.pyplot as plt
x_values = [1,2,3,4,5]
y_values = [1,4,9,16,25]
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.scatter(x_values,y_values,s=100)
# 设置图表标签并给坐标轴加上标签
ax.set_title("平方数",fontsize=24)
ax.set_xlabel("值",fontsize=14)
ax.set_ylabel("值的平方",fontsize=14)
plt.show()
运算结果:
15.2.6 自动计算数据
scatter_squares.py
import matplotlib.pyplot as plt
# x_values = [1,2,3,4,5]
# y_values = [1,4,9,16,25]
x_values = range(1