本小节内容
今天这一小节主要是学Matplotlib绘制折线图、时序数据,以及如何更改图表的某些参数属性。
基础代码
首先,看看基础的Matplotlib的画图代码。一个是单个数据指标画图,还有一个是多个数据指标画图。
# 单个数据输出
# Import the matplotlib.pyplot submodule and name it plt
import matplotlib.pyplot as plt
# Create a Figure and an Axes with plt.subplots
plt.plots(y = xxx, x = xxx, kind = {
'bar', 'scatter', ....})
# Call the show function to show the result
plt.show()
# 多个数据指标画图
# Import the matplotlib.pyplot submodule and name it plt
import matplotlib.pyplot as plt
# Create a Figure and an Axes with plt.subplots
fig, ax = plt.subplots()
ax.plot()
# Call the show function to show the result
plt.show()
实例讲解
在本练习中,我们将使用绘图方法添加两个美国城市的降雨数据:西雅图,华盛顿州和奥斯汀,德克萨斯州。
seattle_weather 存储有关西雅图天气的信息,而 austin_weather 存储有关奥斯汀天气的信息。每个 DataFrame 都有一个“MONTH”列,用于存储月份的三个字母名称。每个还有一个名为“MLY-PRCP-NORMAL”的列,用于存储十年期间每个月的平均降雨量。
关于该数据集的任务如下:
- 通过调用 plt.subplots 创建一个 Figure 和一个 Axes 对象。
- 通过调用 Axes plot 方法从 seattle_weather DataFrame 添加数据。
- 以类似的方式从 austin_weather DataFrame 添加数据并调用 plt.show 以显示结果。
# Import the matplotlib.pyplot submodule and name it plt
import matplotlib.pyplot as plt
# Create a Figure and an Axes with plt.subplots
fig, ax = plt.subplots()
# Plot MLY-PRCP-NORMAL from seattle_weather against the MONTH
ax.plot(seattle_weather["MONTH"], seattle_weather['MLY-PRCP-NORMAL'])
# Plot MLY-PRCP-NORMAL from austin_weather against MONTH
ax.plot(austin_weather['MONTH'], austin_weather['MLY-PRCP-NORMAL'])
# Call the show function
plt.show()
当然,ax不止这一个功能,可以更改标记每个数据点,并更改形状。能改变线条颜色以及线条的风格。代码如下
# Plot Seattle data, setting data appearance
ax.plot(seattle_weather["MONTH"], seattle_weather["MLY-PRCP-NORMAL"], color = 'b', marker = 'o', linestyle = '--')
# Plot Austin data, setting data appearance
ax.plot(austin_weather["MONTH"], austin_weather["MLY-PRCP-NORMAL"], color = 'r', marker = 'v', linestyle = '--')
# Call show to display the resulting plot
plt.show()
如果想自定义x轴、y轴以及标题,可以这么做。
- x轴:ax.set_xlabel(’xxx’)
- y轴:ax.set_ylabel(’xxx’)
- 标题:ax.set_title(’xxx’)
ax.plot(seattle_weather["MONTH"], seattle_weather["MLY-PRCP-NORMAL"])
ax.plot