Python数据分析之matplotlib折线图

Python数据分析之matplotlib折线图

1.需求
  • 需求假设大家在30岁,根据实际情况,统计出你和同桌从11岁倒30岁做成的男女朋友数量,绘出折线图分析自己和同桌的谈恋爱走势
    ‘’’
    a = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1]
    b = [1,0,3,1,2,2,2,3,1,1,1,1,1,2,1,1,2,3,2,2]
    ‘’’
  • 要求y轴表示个数,x轴表示岁数
2.需求分析
  • 1.需要反映走势,采用折线图
  • 2.x轴对应年龄,y轴对应当年的人数
  • 3.对标签部分的汉字进行处理,避免乱码
3.代码示例
# !/usr/bin/python
# Filename: 折线图作业一.py
# Data    : 2020/12/29
# Author  : --king--
# ctrl+alt+L自动加空格格式化

# 需求假设大家在30岁,根据实际情况,统计出你和同桌从11岁倒30岁做成的男女朋友数量,绘出折线图分析自己和同桌的谈恋爱走势
'''
a = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1]
b = [1,0,3,1,2,2,2,3,1,1,1,1,1,2,1,1,2,3,2,2]
'''
# 要求y轴表示个数,x轴表示岁数

from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties

# 设置字体
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)

# 设置y轴对应值
a = [1, 0, 1, 1, 2, 4, 3, 2, 3, 4, 4, 5, 6, 5, 4, 3, 3, 1, 1, 1]
b = [1, 0, 3, 1, 2, 2, 2, 3, 1, 1, 1, 1, 1, 2, 1, 1, 2, 3, 2, 2]

# 设置x轴对应值
x = range(11, 31)

# 创建画布
fig = plt.figure()

# 添加子图ax1
ax1 = plt.subplot(2, 1, 1)

plt.plot(x, a, marker='*', markersize=10, color='g')

# 设置x轴刻度标签
x_t = range(11, 31)
x_l = [f'{i}岁' for i in range(11, 31)]
plt.xticks(x_t, x_l, rotation=45, fontproperties=font)
plt.xlabel('年龄', fontproperties=font)

# 设置y轴刻度标签
y_t = range(0, 7)
y_l = [f'{i}个' for i in range(0, 7)]
plt.yticks(y_t, y_l, fontproperties=font)
plt.ylabel('恋爱人数', fontproperties=font)

plt.title('我的恋爱路线', fontproperties=font)
# 设置网格
plt.grid()

# 添加子图ax2
ax2 = plt.subplot(2, 1, 2)

plt.plot(x, b, marker='o', markersize=10, color='y')

# 设置x轴刻度标签
x_t = range(11, 31)
x_l = [f'{i}岁' for i in range(11, 31)]
plt.xticks(x_t, x_l, rotation=45, fontproperties=font)
plt.xlabel('年龄', fontproperties=font)

# 设置y轴刻度标签
y_t = range(0, 7)
y_l = [f'{i}个' for i in range(0, 7)]
plt.yticks(y_t, y_l, fontproperties=font)
plt.ylabel('恋爱人数', fontproperties=font)

plt.title('同桌的恋爱路线', fontproperties=font)

plt.grid()
plt.show()

在这里插入图片描述

4.总结和思考
  • 1.汉字处理可以采用全局处理的方式,方便很多
    • 全局处理的方式1 :

    import matplotlib
    font = {
    ‘family’:‘SimHei’,
    ‘weight’:‘bold’,
    ‘size’:12
    }
    matplotlib.rc(“font”, **font)

    • 全局处理方式2:

    import matplotlib.pyplot as plt
    plt.rcParams[‘font.sans-serif’] = [‘SimHei’] # 步骤一(替换sans-serif字体)
    plt.rcParams[‘axes.unicode_minus’] = False # 步骤二(解决坐标轴负数的负号显示问题)

  • 2.两张图部分代码重合度较高,可以考虑采用函数的方式写框架
  • 3.subplot(行数, 列数, 第几张图(从1开始))
  • 4.刻度需要一致才能又对比效果,不能单纯的以min(y),max(y)定义y轴
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

kingx3

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值