线条颜色(color)、线型(linestyle)、点标记符(marker)
import matplotlib.pyplot as plt
# 创建一个 figure 对象,相当于一个空白的画布
figure = plt.figure()
# 在画布上添加一个坐标系
axes1 = figure.add_subplot(1, 1, 1)
# 准备画图的数据
x1 = [1, 2, 3, 4, 5, 6, 7]
y1 = [21, 27, 29, 32, 29, 28, 35]
y2 = [20, 25, 30, 31, 27, 30, 30]
# 设置画布的基本元素
axes1.set_xlabel('星期日期')
axes1.set_ylabel('温度')
axes1.set_title("五月每周温度")
# 画图
axes1.plot(x1, y1, color='red', linestyle='-.', marker='*')
axes1.plot(x1, y2, color='blue', linestyle='-', marker='o')
刻度、标签和图例
要改变 x 轴刻度,最简单的办法是使用 set_xticks() 和 set_xticklabels() 。前者告诉 matplotlib 要将刻度放在数据范围中的哪些位置,默认情况下,这些位置也就是刻度标签。但我们可以通过 set_xticklabels() 用任何其他的值用作标签,rotation 选项设定 x 刻度标签倾斜 30 度, fontsize 指定字型大小。在画线的时后直接指定属性 label ,并透过 legend() 函数画出图丽,须指出图例的所在位置,‘best’ 是系统自动配置,也可以选择 ‘upper right’, ‘upper left’, ‘lower left’, ‘lower right’ 等位置。
import matplotlib.pyplot as plt
# 创建一个 figure 对象,相当于一个空白的画布
figure = plt.figure()
# 在画布上添加一个坐标系
axes1 = figure.add_subplot(1, 1, 1)
# 准备画图的数据
x1 = [1, 2, 3, 4, 5, 6, 7]
y1 = [21, 27, 29, 32, 29, 28, 35]
y2 = [20, 25, 30, 31, 27, 30, 30]
axes1.set_xticks(x1)
axes1.set_xticklabels(['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'], rotation=30, fontsize='small')
# 设置画布的基本元素
axes1.set_xlabel('星期日期')
axes1.set_ylabel('温度')
axes1.set_title("五月每周温度")
# 画图
axes1.plot(x1, y1, color='red', linestyle='-.', marker='*', label='第 1 周')
axes1.plot(x1, y2, color='blue', linestyle='-', marker='o', label='第 2 周')
axes1.legend(loc='best')
图 4-2-4 自定刻度并显示图例的画布