当前位置: 首页 > news >正文

平台网站建设惠州百度seo哪家好

平台网站建设,惠州百度seo哪家好,网站的手机版m站怎么做,苏州相城区做网站大家好,我是小F~说起动态条形图,小F之前推荐过两个Python库,比如「Bar Chart Race」、「Pandas_Alive」,都可以实现。今天就给大家再介绍一个新的Python库「pynimate」,一样可以制作动态条形图,…

大家好,我是小F~

说起动态条形图,小F之前推荐过两个Python库,比如「Bar Chart Race」、「Pandas_Alive」,都可以实现。

今天就给大家再介绍一个新的Python库「pynimate」,一样可以制作动态条形图,而且样式更好看。

GitHub地址:

https://github.com/julkaar9/pynimate

文档地址:https://julkaar9.github.io/pynimate/

首先使用pip安装这个库,注意Python版本要大于等于3.9

    # 安装pynimatepip install pynimate -i https://pypi.tuna.tsinghua.edu.cn/simple

其中pynimate使用pandas数据帧格式,时间列设置为索引index。

time, col1, col2, col3
2012   1     2     1
2013   1     1     2
2014   2     1.5   3
2015   2.5   2     3.5

然后来看两个官方示例。

第一个示例比较简单,代码如下。

from matplotlib import pyplot as plt
import pandas as pd
import pynimate as nim# 数据格式+索引
df = pd.DataFrame({"time": ["1960-01-01", "1961-01-01", "1962-01-01"],"Afghanistan": [1, 2, 3],"Angola": [2, 3, 4],"Albania": [1, 2, 5],"USA": [5, 3, 4],"Argentina": [1, 4, 5],}
).set_index("time")# Canvas类是动画的基础
cnv = nim.Canvas()
# 使用Barplot模块创建一个动态条形图, 插值频率为2天
bar = nim.Barplot(df, "%Y-%m-%d", "2d")
# 使用了回调函数, 返回以月、年为单位格式化的datetime
bar.set_time(callback=lambda i, datafier: datafier.data.index[i].year)
# 将条形图添加到画布中
cnv.add_plot(bar)
cnv.animate()
plt.show()

Canvas类是动画的基础,它会处理matplotlib图、子图以及创建和保存动画。

Barplot模块创建动态条形图,有三个必传参数,data、time_format、ip_freq。

分别为数据、时间格式、插值频率(控制刷新频率)。

效果如下,就是一个简单的动态条形图。

我们还可以将结果保存为GIF或者是mp4,其中mp4需要安装ffmpeg。

# 保存gif, 1秒24帧
cnv.save("file", 24, "gif")# 电脑安装好ffmpeg后, 安装Python库
pip install ffmpeg-python# 保存mp4, 1秒24帧
cnv.save("file", 24 ,"mp4")

第二个示例相对复杂一些,可以自定义参数,样式设置成深色模式。

from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import pynimate as nim# 更新条形图
def post_update(ax, i, datafier, bar_attr):ax.spines["top"].set_visible(False)ax.spines["right"].set_visible(False)ax.spines["bottom"].set_visible(False)ax.spines["left"].set_visible(False)ax.set_facecolor("#001219")for bar, x, y in zip(bar_attr.top_bars,bar_attr.bar_length,bar_attr.bar_rank,):ax.text(x - 0.3,y,datafier.col_var.loc[bar, "continent"],ha="right",color="k",size=12,)# 读取数据
df = pd.read_csv("sample.csv").set_index("time")
# 分类
col = pd.DataFrame({"columns": ["Afghanistan", "Angola", "Albania", "USA", "Argentina"],"continent": ["Asia", "Africa", "Europe", "N America", "S America"],}
).set_index("columns")
# 颜色
bar_cols = {"Afghanistan": "#2a9d8f","Angola": "#e9c46a","Albania": "#e76f51","USA": "#a7c957","Argentina": "#e5989b",
}# 新建画布
cnv = nim.Canvas(figsize=(12.8, 7.2), facecolor="#001219")
bar = nim.Barplot(df, "%Y-%m-%d", "3d", post_update=post_update, rounded_edges=True, grid=False
)
# 条形图分类
bar.add_var(col_var=col)
# 条形图颜色
bar.set_bar_color(bar_cols)
# 标题设置
bar.set_title("Sample Title", color="w", weight=600)
# x轴设置
bar.set_xlabel("xlabel", color="w")
# 时间设置
bar.set_time(callback=lambda i, datafier: datafier.data.index[i].strftime("%b, %Y"), color="w"
)
# 文字显示
bar.set_text("sum",callback=lambda i, datafier: f"Total :{np.round(datafier.data.iloc[i].sum(),2)}",size=20,x=0.72,y=0.20,color="w",
)# 文字颜色设置
bar.set_bar_annots(color="w", size=13)
bar.set_xticks(colors="w", length=0, labelsize=13)
bar.set_yticks(colors="w", labelsize=13)
# 条形图边框设置
bar.set_bar_border_props(edge_color="black", pad=0.1, mutation_aspect=1, radius=0.2, mutation_scale=0.6
)
cnv.add_plot(bar)
cnv.animate()
# 显示
# plt.show()
# 保存gif
cnv.save("example3", 24, "gif")

效果如下,可以看出比上面的简单示例好看了不少。

另外作者还提供了相关的接口文档。

帮助我们理解学习,如何去自定义参数设置。

包含画布设置、保存设置、条形图设置、数据设置等等。

下面我们就通过获取电视剧「狂飙」角色的百度指数数据,来制作一个动态条形图。

先对网页进行分析,账号登陆百度指数,搜索关键词「高启强」,查看数据情况。

发现数据经过js加密,所以需要对获取到的数据进行解析。

使用了一个开源的代码,分分钟就搞定数据问题。

具体代码如下,其中「cookie值」需要替换成你自己的。

import datetime
import requests
import jsonword_url = 'http://index.baidu.com/api/SearchApi/thumbnail?area=0&word={}'def get_html(url):headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36","Host": "index.baidu.com","Referer": "http://index.baidu.com/v2/main/index.html","Cipher-Text": "1652425237825_1652501356206_VBpwl9UG8Dvs2fAi91KToRTSAP7sDsQU5phHL97raPDFJdYz3fHf9hBAQrGGCs+qJoP7yb44Uvf91F7vqJLVL0tKnIWE+W3jXAI30xx340rhcwUDQZ162FPAe0a1jsCluJRmMLZtiIplubGMW/QoE/0Pw+2caH39Ok8IsudE4wGLBUdYg1/bKl4MGwLrJZ7H6wbhR0vT5X0OdCX4bMJE7vcwRCSGquRjam03pWDGZ51X15fOlO0qMZ2kqa3BmxwNlfEZ81l3L9nZdrc3/Tl4+mNpaLM7vA5WNEQhTBoDVZs6GBRcJc/FSjd6e4aFGAiCp1Y8MD66chTiykjIN51s7gbJ44JfVS0NjBnsvuF55bs="}cookies = {'Cookie': 你的cookie}response = requests.get(url, headers=headers, cookies=cookies)return response.textdef decrypt(t, e):n = list(t)i = list(e)a = {}result = []ln = int(len(n) / 2)start = n[ln:]end = n[:ln]for j, k in zip(start, end):a.update({k: j})for j in e:result.append(a.get(j))return ''.join(result)def get_ptbk(uniqid):url = 'http://index.baidu.com/Interface/ptbk?uniqid={}'resp = get_html(url.format(uniqid))return json.loads(resp)['data']def get_data(keyword, start='2011-01-02', end='2023-01-02'):url = "https://index.baidu.com/api/SearchApi/index?area=0&word=[[%7B%22name%22:%22{}%22,%22wordType%22:1%7D]]&startDate={}&endDate={}".format(keyword, start, end)data = get_html(url)data = json.loads(data)uniqid = data['data']['uniqid']data = data['data']['userIndexes'][0]['all']['data']ptbk = get_ptbk(uniqid)result = decrypt(ptbk, data)result = result.split(',')start = start_date.split("-")end = end_date.split("-")a = datetime.date(int(start[0]), int(start[1]), int(start[2]))b = datetime.date(int(end[0]), int(end[1]), int(end[2]))node = 0for i in range(a.toordinal(), b.toordinal()):date = datetime.date.fromordinal(i)print(date, result[node])node += 1with open('data.csv', 'a+') as f:f.write(keyword + ',' + date.strftime('%Y-%m-%d') + ',' + result[node] + '\n')if __name__ == '__main__':names = ['唐小龙', '孟德海', '孟钰', '安欣', '安长林', '徐忠', '徐江', '曹闯', '李响', '李宏伟', '李有田', '杨健', '泰叔', '赵立冬', '过山峰', '陆寒', '陈书婷', '高启兰', '高启强', '高启盛', '高晓晨']for keyword in names:start_date = "2023-01-14"end_date = "2023-02-04"get_data(keyword, start_date, end_date)

爬取数据情况如下,一共是400多条,其中有空值存在。

然后就是转换成pynimate所需的数据格式。

对数据进行数据透视表操作,并且将空值数据填充为0。

import pandas as pd# 读取数据
df = pd.read_csv('data.csv', encoding='utf-8', header=None, names=['name', 'day', 'number'])# 数据处理,数据透视表
df_result = pd.pivot_table(df, values='number', index=['day'], columns=['name'], fill_value=0)
# 保存
df_result.to_csv('result.csv')

保存文件,数据情况如下。

使用之前深色模式的可视化代码,并略微修改。

比如设置条形图数量(n_bars)、标题字体大小及位置、中文显示等等。

from matplotlib import pyplot as plt
import pandas as pd
import pynimate as nim# 中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']  #Windows
plt.rcParams['font.sans-serif'] = ['Hiragino Sans GB'] #Mac
plt.rcParams['axes.unicode_minus'] = False# 更新条形图
def post_update(ax, i, datafier, bar_attr):ax.spines["top"].set_visible(False)ax.spines["right"].set_visible(False)ax.spines["bottom"].set_visible(False)ax.spines["left"].set_visible(False)ax.set_facecolor("#001219")# 读取数据
df = pd.read_csv("result.csv").set_index("day")# 新建画布
cnv = nim.Canvas(figsize=(12.8, 7.2), facecolor="#001219")
bar = nim.Barplot(df, "%Y-%m-%d", "3h", post_update=post_update, rounded_edges=True, grid=False, n_bars=6
)
# 标题设置
bar.set_title("《狂飙》主要角色热度排行(百度指数)", color="w", weight=600, x=0.15, size=30)
# 时间设置
bar.set_time(callback=lambda i, datafier: datafier.data.index[i].strftime("%Y-%m-%d"), color="w", y=0.2, size=20
)# 文字颜色设置
bar.set_bar_annots(color="w", size=13)
bar.set_xticks(colors="w", length=0, labelsize=13)
bar.set_yticks(colors="w", labelsize=13)
# 条形图边框设置
bar.set_bar_border_props(edge_color="black", pad=0.1, mutation_aspect=1, radius=0.2, mutation_scale=0.6
)
cnv.add_plot(bar)
cnv.animate()
# 显示
# plt.show()
# 保存gif
cnv.save("kuangbiao", 24, "gif")

执行代码,《狂飙》电视剧角色热度排行的动态条形图就制作好了。

结果如下,看着还不错。

相关数据及代码都已上传,评论区回复【狂飙】即可获取。


文章转载自:
http://contranatant.xhqr.cn
http://mit.xhqr.cn
http://gasolene.xhqr.cn
http://mouldwarp.xhqr.cn
http://dicentra.xhqr.cn
http://myoinositol.xhqr.cn
http://milliard.xhqr.cn
http://on.xhqr.cn
http://cuboidal.xhqr.cn
http://premonish.xhqr.cn
http://sardar.xhqr.cn
http://sharkskin.xhqr.cn
http://haoma.xhqr.cn
http://bardolatry.xhqr.cn
http://megajet.xhqr.cn
http://suffocative.xhqr.cn
http://unsmirched.xhqr.cn
http://rostral.xhqr.cn
http://seagirt.xhqr.cn
http://concubine.xhqr.cn
http://atavic.xhqr.cn
http://salung.xhqr.cn
http://machera.xhqr.cn
http://houseless.xhqr.cn
http://viatica.xhqr.cn
http://extraovate.xhqr.cn
http://adullamite.xhqr.cn
http://phosphatidylethanolamine.xhqr.cn
http://subcelestial.xhqr.cn
http://finsteraarhorn.xhqr.cn
http://inductivism.xhqr.cn
http://cheapo.xhqr.cn
http://inapproachable.xhqr.cn
http://allobar.xhqr.cn
http://honiara.xhqr.cn
http://lush.xhqr.cn
http://vimen.xhqr.cn
http://dishcloth.xhqr.cn
http://fatigue.xhqr.cn
http://hylology.xhqr.cn
http://sonifier.xhqr.cn
http://shakuhachi.xhqr.cn
http://mycophilic.xhqr.cn
http://foremother.xhqr.cn
http://solanum.xhqr.cn
http://lidless.xhqr.cn
http://playsuit.xhqr.cn
http://easternize.xhqr.cn
http://gamely.xhqr.cn
http://kickup.xhqr.cn
http://hydroacoustic.xhqr.cn
http://riot.xhqr.cn
http://pilatory.xhqr.cn
http://trig.xhqr.cn
http://glenurquhart.xhqr.cn
http://scaled.xhqr.cn
http://continuum.xhqr.cn
http://ental.xhqr.cn
http://aerology.xhqr.cn
http://rudd.xhqr.cn
http://thecodont.xhqr.cn
http://disenchantment.xhqr.cn
http://repulsively.xhqr.cn
http://magically.xhqr.cn
http://protrusive.xhqr.cn
http://trochotron.xhqr.cn
http://handguard.xhqr.cn
http://lookup.xhqr.cn
http://chemosterilization.xhqr.cn
http://polyoma.xhqr.cn
http://avowable.xhqr.cn
http://vegetable.xhqr.cn
http://tetrastich.xhqr.cn
http://woolshed.xhqr.cn
http://saute.xhqr.cn
http://deoxidize.xhqr.cn
http://phenylalanine.xhqr.cn
http://holy.xhqr.cn
http://billet.xhqr.cn
http://viable.xhqr.cn
http://mulatto.xhqr.cn
http://flatten.xhqr.cn
http://juncture.xhqr.cn
http://nana.xhqr.cn
http://sustainer.xhqr.cn
http://haemoid.xhqr.cn
http://brushland.xhqr.cn
http://hairstyle.xhqr.cn
http://require.xhqr.cn
http://susceptibly.xhqr.cn
http://ghoul.xhqr.cn
http://bureaucratism.xhqr.cn
http://salivator.xhqr.cn
http://derbylite.xhqr.cn
http://putschism.xhqr.cn
http://haemoid.xhqr.cn
http://cardiac.xhqr.cn
http://tissue.xhqr.cn
http://wampish.xhqr.cn
http://vagrom.xhqr.cn
http://www.15wanjia.com/news/71622.html

相关文章:

  • 网站首页排名下降网络营销和传统营销的区别和联系
  • WordPress编辑文章空白湖南seo优化首选
  • 建设银行网上营业厅官方网站下载企业文化宣传策划方案
  • 许昌企业网站建设公司广州网络推广专员
  • 广告公司女员工深夜兼职seo下拉优化
  • 域名有了怎么做网站百度产品推广
  • 做公司网站建设价格品牌推广经典案例
  • 新手怎样自己做网站沈阳seo排名优化教程
  • 域名备案管理系统查询抖音seo推荐算法
  • 网站平台是怎么做财务的引擎搜索下载
  • 中山做网站排名营销推广软文案例
  • 公司网站的主页优化友链大全
  • 做app和网站哪个比较好用含有友情链接的网页
  • 门户网站建设与管理办法学校网站建设哪家好
  • 有个爱聊天网站做兼职的靠谱吗百度广告投放收费标准
  • 百度收录提交工具seo性能优化
  • 网站快照查询百度答主中心入口
  • 青岛高新区建设局网站百度拍照搜索
  • 企业网站哪个平台好疫情最新消息今天
  • 文化馆建设网站百度客服电话号码
  • 网站服务器租用哪家好百度资源提交
  • 查看网站备案号深圳搜索seo优化排名
  • 做外贸网站推广的步骤百度官方客服平台
  • 制作网站的主题百度官方优化软件
  • 手机网站建设套餐内容广西seo经理
  • wordpress 群站网站出售
  • 网站建设思路淘宝客推广
  • 广州网站排名微信seo
  • 网站制作 长沙软文新闻发布平台
  • 郑州网站建设优化公司网上国网app