Python数据可视化 Matplotlib详解(一) —— 折线图与时序数据绘制


本小节内容

今天这一小节主要是学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
  • 5
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Pigou_

谢谢老板!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值