pyecharts绘制动态图表


写在前面

本文来自微信公众号:python数据分析之禅,创作不易,请支持原作者。

获取数据

#用到的包
import requests
from bs4 import BeautifulSoup as bs
import time
import csv
import schedule
#微博热搜地址
BASE_URL = 'https://s.weibo.com/top/summary'
#创建csv文件,并填入表头
with open('1.csv','wt',newline = '') as f:
    f_csv = csv.writer(f)
    f_csv.writerow(['时间','排名','热度','内容'])
#设置请求头
headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0'
    }
#爬取数据
def run():
    #请求热搜地址
    res = requests.get(url = BASE_URL,headers = headers)
    res.encoding = res.apparent_encoding
    #使用BeautifulSoup解析网页
    html = bs(res.text,'lxml')
    items = html.find_all('td',class_ = "td-02")
    #获取当前时间并格式化
    time_stramp = time.strftime('%Y/%m/%d %H:%M',time.localtime())
    #枚举热搜榜前10
    for i,item in enumerate(items[1:11]):
        #空列表用于保存一条数据
        result = []
        #根据顺序排名
        rank = '第{0}名'.format(i + 1)
        #获取热度
        num = item.find('span').text
        #获取热搜标题
        title = item.find('a').text
        #添加到列表中
        result.append(time_stramp)
        result.append(rank)
        result.append(num)
        result.append(title)
        #将列表写入csv文件
        with open('1.csv','a+',newline = '') as f:
            f_csv = csv.writer(f)
            f_csv.writerow(result)
    #输出时间
    print(time_stramp)
#设定计划,微博热搜每分钟更新一次,所以每分钟执行一次
schedule.every(1).minutes.do(run)
#开始执行计划
while True:
    schedule.run_pending()

让数据动起来

#用到的包
from pyecharts import options as opts
from pyecharts.charts import Bar,Timeline,Grid
from pyecharts.globals import ThemeType
import pandas as pd
import pyecharts.globals
from pyecharts.globals import CurrentConfig
import warnings
#禁用警告
warnings.filterwarnings("ignore")
#禁用pyecharts1.9.0安全警告
pyecharts.globals._WarningControl.ShowWarning = False
#更改静态文件目录,你需要将js文件移到对应的目录下
CurrentConfig.ONLINE_HOST = "./js/"
#从csv文件读入数据
data = pd.read_csv('1.csv',encoding = 'gbk')
#创建Timeline对象,用于按顺序演示数据,theme是一种图表风格
tl = Timeline({'theme':ThemeType.MACARONS})
#如果数据更多的话,可以修改range后面括号中的数字
for i in range(20):
    #创建柱形图
    bar = (
        Bar({'theme':ThemeType.MACARONS})
        .add_xaxis(list(data['内容'])[i*10:i*10+10][::-1])#横坐标(标题)
        .add_yaxis('微博热搜榜',list(data['热度'])[i*10:i*10+10][::-1])#纵坐标(热度)
        .reversal_axis()#图形反转
        #添加时间标签
        .set_global_opts(
            title_opts = opts.TitleOpts("{}".format(list(data['时间'])[i*10]),pos_right = '0%',pos_bottom = '15%'),
            xaxis_opts = opts.AxisOpts(
                splitline_opts = opts.SplitLineOpts(is_show = True),
                position = 'top',
                name_gap = 10,
                boundary_gap = ['20%','20%']),
            yaxis_opts = opts.AxisOpts(splitline_opts = opts.SplitLineOpts(is_show = True),
                                       axislabel_opts = opts.LabelOpts(color = '#FF7F50')),)
        .set_series_opts(label_opts = opts.LabelOpts(position = 'right',color = "#9400D3"))#将标签放在图形右边
        )
    grid = (
        Grid()
        .add(bar,grid_opts = opts.GridOpts(pos_left = "25%",pos_right = "0%"))#图形整体右移
        )
    tl.add(grid,"{}年".format(i))
    tl.add_schema(
        #设置播放速度(单位应该是毫秒)
        play_interval = 100,
        #是否隐藏timeline组件
        is_timeline_show = False,
        #是否自动播放
        is_auto_play = True,
        )
#保存绘制的图表
tl.render('微博热搜.html')

写在后面

不得不说,仍没有透彻理解pyecharts的绘图规则,但是这个似乎还挺好玩,也有一定的视觉效果。 ps:爬取热搜数据需要自行设定次数或在爬取足量数据后手动打断。