Python3 + matplotlib.pyplot 实现数据可视化(折线图)

Python3 + matplotlib.pyplot 实现数据可视化(折线图)

需求

通过已有数据文件(链接: 数据文件来源.)拿到数据,筛选毒菌相关的我的评论,并使用matplotlib.pyplot画出筛选后的评论按日期分布折线图,实现数据可视化

代码

import datetime
import re

import matplotlib.pyplot as plt

first_date, last_date = '2020-01-01', '2020-11-01'

def comm_msg(path):
    day_num = (datetime.datetime.strptime(last_date, '%Y-%m-%d') -
               datetime.datetime.strptime(first_date, '%Y-%m-%d')).days + 1  # 总天数
    data_dict = dict([((datetime.datetime.strptime(first_date, '%Y-%m-%d') +
                        datetime.timedelta(days=i)).strftime('%m.%d'), 0) for i in range(day_num)])
    super_poisonous_mushrooms = ['青褶伞', '日本红菇', '盔孢伞', '卷边桩菇', '黄盖鹅膏', '肉褐鳞环柄菇', '亚稀褶红菇',
                                 '鹿花菌', '丝盖伞']
    poisonous_regular_strs = ['[^没无]毒|^毒', '头晕|头痛', '腹泻|肠胃炎', '[^牛]肝|^肝', '肾[^形]|肾$', '内脏损伤',
                              '致命|要命|生命危险', '|'.join(super_poisonous_mushrooms)]

    with open(path, 'r', encoding='utf-8') as f:
        for l in f:
            l = l.split('\t')
            comm_time, comm_text = l[3], l[2]
            if comm_time.startswith('2020'):
                matched_str = comm_text.split('</a>:')[-1]
                if '</a>:' in matched_str:
                    matched_str = comm_text.split('</a>:')[-1]  # 防止被回答者id带关键字
                for prs in poisonous_regular_strs:  # 是否符合任一条目标正则
                    if re.findall(prs, matched_str):
                        data_dict[comm_time.replace('-', '.')[5:10]] += 1  # 筛过处理
                        break
    return list(data_dict.keys()), list(data_dict.values())


plt.rcParams['font.sans-serif'] = ['simsun']  # 宋体
x_date_data, y_comm_data = comm_msg(r'D:\xxx\data.txt')
interval_x = 20  # 隔几单位显示一次日期
plt.xticks(range(len(x_date_data)), [x_date_data[i] if i % interval_x == 0 else ' ' for i in range(len(x_date_data))])  # x轴日期标注
plt.axis([-1, len(x_date_data), 0, ((max(y_comm_data) - 1) // 10 + 1) * 10])  # 横纵坐标边界
plt.grid()  # 网格
plt.plot(x_date_data, y_comm_data, c='red')
plt.legend(['涉及毒菌评论总数'], loc='upper left')
plt.show()

效果图:
效果折线图

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值