本文主要是介绍数据可视化|基于Python数据清洗的Chart Race图,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
打开抖音、微博、小红书,每当刷到这种Chart Race图,你是否常为之一振!😆
像这样:
各国冠状病毒数据变化图
这样:
近二十年各省人口变化图
还有这样:
世界各国平均预期寿命变化图
WoW,一个比一个Shocking有没有??🤔
作为计算机专业的学(F)子(W),每每看到这些之后,心中都充斥着achieve它的想法。然后想法就是想法,想想就过了。连遇到困难睡大觉的机会都没有…🤪
近日闲着无聊,又刷到了类似的Chart Race图,这一次,终于草草的实现了两种简单的Race图。
第一种,利用 Power BI 实现
在搜集资料和方法的过程中,我发现了一位 UP主利用Power BI自带的插件制作出了朴素的Chart Race图。全程没有任何代码操作,虽说很无趣,但这里也介绍一下,以表示对没学过编程的小白的友好🥳
1-1、Power BI Desktop下载(免费)
下载链接: https://powerbi.microsoft.com/zh-cn/desktop.
1-2、Animated Bar Chart Race插件下载(动态条形图)
下载链接: https://appsource.microsoft.com/zh-cn/marketplace/apps?src=office&search=Animated%20Bar%20Chart%20Race&page=1.
1-3、准备数据并导入
1-3-1 下载数据
到国家统计局网站下载所需要的excel文件(此方法必须下载excel格式的文件)
链接: 国家统计局官网.
1-3-2 整理数据
将excel以Excel方式打开,去除多余的部分,只留下主体数据
1-3-3 筛选数据
利用Excel的立透视功能,整理数据。
点击 数据—来自表格/区域—确定,
点击 转换—逆透视列右边的倒三角,选择逆透视其他列
结果如下图:
点击 主页—关闭并上载
结果如下图:
如果要用其他数据,必须要有名字、属性、值三列数据。
1-3-4 导入Animated Bar Chart Race插件和数据文件
从文件导入Animated Bar Chart Race
点击 主页的获取数据—Excel工作簿—选择整理好的excel文件及表—加载
成功导入后出现表1,如下图:
1-4、匹配数据,完成制作
Name、Value、 Period分别对应数据文件的每一列
将右边三列分别拖到对应位置
为了Period好看,只保留年,其他都叉掉
已经基本完成了,再修改一下格式、主题等美化一下就可以了。😌
第二种,基于Python数据清洗的Chart Race图
上一种方法虽然简单好上手,但细心的小伙伴很快就能发现,这种方法制作的Chart Race图很差劲。毕竟太机械的手段,做出来十分生硬,既不好看也不太实用。那么,以下基于Python和js的方法,是比较好用也比较好看的。
2-1、利用Python预处理数据
首先和第一种方法一样到国家统计局官网下载数据文件,这次需要的是.csv文件
。
# -*- coding : utf-8 -*-
# coding: utf-8
import pandas as pd
import numpy as np# 读取数据
filepath = "D:\\Users\\玖玖\\Desktop\\人口.csv"
df = pd.read_csv( filepath, encoding= "GBK" )
(names, values, dates) = ([], [], [])
# 去除地区这个列名,遍历年份
for i in df.columns[1:]:for j, k in zip(df[i], df["地区"]):# 输出地区、GDP值、年份数据print(k, j, i)names.append(k)if not np.isnan(j):values.append(int(j))else:values.append(0)dates.append(int(i.replace("年", "")))
# 构建我们需要的格式
data = {"name": names,"type": "","value": values,"date": dates
}# 将数据转存为新的CSV文件
frame = pd.DataFrame(data)
# index = False 即不需要第一列序号
frame.to_csv("预处理1.csv", encoding="utf_8_sig", index=False)
如果是国家统计局的数据,因为数据是从近年往前排列的,所以此时"预处理1.csv"数值大的年份在前面,可以用下列方法按年份逆序排列,使得数据按年份大小从小到大排列。
from operator import itemgetter#导入定位的头方便定位按照哪里排序
import pandas as pd
import numpy as npi=0#初始化变量with open('data_人口.csv',encoding='utf-8') as f:#打开文件地址table=[]#开个列表No1=f.readline()#读取一行因为我的第一行是目录所有先读取了就不用计算了print(No1)#输出目录for line in f:#从现在的第二行开始找,因为上一步的操作把当前指针指向了第二行了col = line.split(',')#把每列数据分割开col[2] = int(col[2])col[3] = int(col[3])#把第4列的用float类型存table.append(col)#把排序后的数据存到列表table_sorted = sorted(table, key=itemgetter(3), reverse=False) # 精确的按照第4列排序table_sorted.insert(0, ["name", "type", "value", "date"]) # 插入表头for row in table_sorted:print(row)#输出每行数据frame =pd.DataFrame(table_sorted)
# index = False 即不需要第一列序号
# header = None 即不需要表头(列序号)
frame.to_csv("预处理2.csv", encoding="utf_8_sig", index=False,header=None)
2-2、Js制作Chart Race图效果
部分代码:
function getCurrentData(date) {rate = [];currentData = [];indexList = [];data.forEach(element => {if (element["date"] == date && parseFloat(element["value"]) != 0) {if (element.name.length > config.bar_name_max) {tail = "...";} else {tail = "";}element.name = element.name.slice(0, config.bar_name_max - 1) + tail;currentData.push(element);}});rate["MAX_RATE"] = 0;rate["MIN_RATE"] = 1;currentData.forEach(e => {_cName = e.name;lastData.forEach(el => {if (el.name == e.name) {rate[e.name] = Number(Number(e.value) - Number(el.value));}});if (rate[e.name] == undefined) {rate[e.name] = rate["MIN_RATE"];}if (rate[e.name] > rate["MAX_RATE"]) {rate["MAX_RATE"] = rate[e.name];} else if (rate[e.name] < rate["MIN_RATE"]) {rate["MIN_RATE"] = rate[e.name];}});// sort and pick the top max_number datadataSort();currentData = currentData.slice(0, max_number);d3.transition("2").each(redraw).each(change);lastData = currentData;}if (showMessage) {// 左1文字var topInfo = g.insert("text").attr("class", "growth").attr("x", 0).attr("y", text_y).text(itemLabel);// 右1文字g.insert("text").attr("class", "growth").attr("x", text_x).attr("y", text_y).text(typeLabel);// 榜首日期计数if (use_counter == true) {var days = g.insert("text").attr("class", "days").attr("x", text_x + offset).attr("y", text_y);} else {// 显示榜首typeif (use_type_info == true) {var top_type = g.insert("text").attr("class", "days").attr("x", text_x + offset).attr("y", text_y);}}}var lastname;var counter = {value: 1};var avg = 0;var enter_from_now = true;function redraw() {if (currentData.length == 0) return;// yScale// .domain(currentData.map(d => d.name).reverse())// .range([innerHeight, 0]);// x轴范围// 如果所有数字很大导致拉不开差距if (big_value) {xScale.domain([2 * d3.min(currentData, xValue) - d3.max(currentData, xValue),d3.max(currentData, xValue) + 10]).range([0, innerWidth]);} else {xScale.domain([0, d3.max(currentData, xValue) + 1]).range([0, innerWidth]);}if (auto_sort) {dateLabel.data(currentData).transition().duration(baseTime * interval_time).ease(d3.easeLinear).tween("text", function (d) {var self = this;var i = d3.interpolateDate(new Date(self.textContent),new Date(d.date));// var prec = (new Date(d.date) + "").split(".");// var round = (prec.length > 1) ? Math.pow(10, prec[1].length) : 1;return function (t) {var dateformat = d3.timeFormat(timeFormat);self.textContent = dateformat(i(t));};});} else {dateLabel.text(currentdate);}xAxisG.transition().duration(baseTime * interval_time).ease(d3.easeLinear).call(xAxis);yAxisG.transition().duration(baseTime * interval_time).ease(d3.easeLinear).call(yAxis);yAxisG.selectAll(".tick").remove();if (!config.show_x_tick) {xAxisG.selectAll(".tick").remove();}yScale.domain(currentData.map(d => d.name).reverse()).range([innerHeight, 0]);var bar = g.selectAll(".bar").data(currentData, function (d) {return d.name;});if (showMessage) {// 榜首文字topLabel.data(currentData).text(function (d) {if (lastname == d.name) {counter.value = counter.value + step;} else {counter.value = 1;}lastname = d.name;if (d.name.length > 24) return d.name.slice(0, 23) + "...";return d.name;});if (use_counter == true) {// 榜首持续时间更新days.data(currentData).transition().duration(baseTime * interval_time).ease(d3.easeLinear).tween("text", function (d) {var self = this;var i = d3.interpolate(self.textContent, counter.value),prec = (counter.value + "").split("."),round = prec.length > 1 ? Math.pow(10, prec[1].length) : 1;return function (t) {self.textContent = d3.format(format)(Math.round(i(t) * round) / round);};});} else if (use_type_info == true) {// 榜首type更新top_type.data(currentData).text(function (d) {return d["type"];});}}var barEnter = bar.enter().insert("g", ".axis").attr("class", "bar").attr("transform", function (d) {return "translate(0," + yScale(yValue(d)) + ")";});barEnter.append("rect").attr("width", function (d) {if (enter_from_0) {return 0;} else {return xScale(currentData[currentData.length - 1].value);}}).attr("fill-opacity", 0).attr("height", 26).attr("y", 50).style("fill", d => getColor(d)).transition("a").delay(500 * interval_time).duration(2490 * interval_time).attr("y", 0).attr("width", d => xScale(xValue(d))).attr("fill-opacity", 1);if (config.rounded_rectangle) {d3.selectAll("rect").attr("rx", 13);}if (config.showLabel == true) {barEnter.append("text").attr("y", 50).attr("fill-opacity", 0).style("fill", d => getColor(d)).transition("2").delay(500 * interval_time).duration(2490 * interval_time).attr("fill-opacity", 1).attr("y", 0).attr("class", function (d) {return "label ";}).attr("x", config.labelx).attr("y", 20).attr("text-anchor", "end").text(function (d) {if (long) {return "";}return d.name;});}if (config.use_img) {barEnter.append("defs").append("pattern").attr("id", d => d.name).attr("width", "100%").attr("height", "100%").append("image").attr("x", "0").attr("y", "0").attr("width", "40").attr("height", "40").attr("href", d => config.imgs[d.name]);barEnter.append("circle").attr("fill-opacity", 0).attr("cy", 63).attr("fill",d =>"url(#" +encodeURIComponent(d.name).replace("'", "%27").replace("(", "%28").replace(")", "%29") +")").attr("stroke-width", "0px").transition("a").delay(500 * interval_time).duration(2490 * interval_time)// .attr("stroke", d => getColor(d))// .attr("paint-order", "stroke").attr("x", -16).attr("cx", d => xScale(xValue(d)) - 20).attr("cy", 13).attr("r", 40 / 2).attr("fill-opacity", 1);}// bar上文字var barInfo = barEnter.append("text").attr("x", function (d) {if (long) return 10;if (enter_from_0) {return 0;} else {return xScale(currentData[currentData.length - 1].value);}}).attr("stroke", d => getColor(d)).attr("class", function () {return "barInfo";}).attr("y", 50).attr("stroke-width", "0px").attr("fill-opacity", 0).transition().delay(500 * interval_time).duration(2490 * interval_time).text(function (d) {if (use_type_info) {return d[divide_by] + "-" + d.name;}return d.name;}).attr("x", d => {if (long) return 10;return xScale(xValue(d)) - 40;}).attr("fill-opacity", function (d) {if (xScale(xValue(d)) - 40 < display_barInfo) {return 0;}return 1;}).attr("y", 2).attr("dy", ".5em").attr("text-anchor", function () {if (long) return "start";return "end";}).attr("stroke-width", function (d) {if (xScale(xValue(d)) - 40 < display_barInfo) {return "0px";}return "4px";}).attr("paint-order", "stroke");if (long) {barInfo.tween("text", function (d) {var self = this;self.textContent = d.value;var i = d3.interpolate(self.textContent, Number(d.value)),prec = (Number(d.value) + "").split("."),round = prec.length > 1 ? Math.pow(10, prec[1].length) : 1;return function (t) {self.textContent =d[divide_by] +"-" +d.name +" 数值:" +d3.format(format)(Math.round(i(t) * round) / round);};});}if (!long) {barEnter.append("text").attr("x", function () {if (long) {return 10;}if (enter_from_0) {return 0;} else {return xScale(currentData[currentData.length - 1].value);}}).attr("y", 50).attr("fill-opacity", 0).style("fill", d => getColor(d)).transition().duration(2990 * interval_time).tween("text", function (d) {var self = this;// 初始值为d.value的0.9倍self.textContent = d.value * 0.9;var i = d3.interpolate(self.textContent, Number(d.value)),prec = (Number(d.value) + "").split("."),round = prec.length > 1 ? Math.pow(10, prec[1].length) : 1;// d.value = self.textContentreturn function (t) {self.textContent =d3.format(format)(Math.round(i(t) * round) / round) +config.postfix;// d.value = self.textContent};}).attr("fill-opacity", 1).attr("y", 0).attr("class", function (d) {return "value";}).attr("x", d => {return xScale(xValue(d)) + 10;}).attr("y", 22);}var barUpdate = bar.transition("2").duration(2990 * interval_time).ease(d3.easeLinear);barUpdate.select("rect").style("fill", d => getColor(d)).attr("width", d => xScale(xValue(d)));if (config.showLabel == true) {barUpdate.select(".label").attr("class", function (d) {return "label ";}).style("fill", d => getColor(d)).attr("width", d => xScale(xValue(d)));}if (!long) {barUpdate.select(".value").attr("class", function (d) {return "value";}).style("fill", d => getColor(d)).attr("width", d => xScale(xValue(d)));}barUpdate.select(".barInfo").attr("stroke", function (d) {return getColor(d);});if (config.use_img) {barUpdate.select("circle").attr("stroke", function (d) {return getColor(d);}).attr("cx", d => xScale(xValue(d)) - 20);}var barInfo = barUpdate.select(".barInfo").text(function (d) {if (use_type_info) {return d[divide_by] + "-" + d.name;}return d.name;}).attr("x", d => {if (long) return 10;return xScale(xValue(d)) - 40;}).attr("fill-opacity", function (d) {if (xScale(xValue(d)) - 40 < display_barInfo) {return 0;}return 1;}).attr("stroke-width", function (d) {if (xScale(xValue(d)) - 40 < display_barInfo) {return "0px";}return "4px";}).attr("paint-order", "stroke");if (long) {barInfo.tween("text", function (d) {var self = this;var str = d[divide_by] + "-" + d.name + " 数值:";var i = d3.interpolate(self.textContent.slice(str.length, 99),Number(d.value)),prec = (Number(d.value) + "").split("."),round = prec.length > 1 ? Math.pow(10, prec[1].length) : 1;return function (t) {self.textContent =d[divide_by] +"-" +d.name +" 数值:" +d3.format(format)(Math.round(i(t) * round) / round);};});}if (!long) {barUpdate.select(".value").tween("text", function (d) {var self = this;// if postfix is blank, do not slice.if (config.postfix == "") {var i = d3.interpolate(self.textContent, Number(d.value));} else {var i = d3.interpolate(self.textContent.slice(0, -config.postfix.length),Number(d.value));}var i = d3.interpolate(deformat(self.textContent, config.postfix),Number(d.value));var prec = (Number(d.value) + "").split("."),round = prec.length > 1 ? Math.pow(10, prec[1].length) : 1;// d.value = self.textContentreturn function (t) {self.textContent =d3.format(format)(Math.round(i(t) * round) / round) +config.postfix;// d.value = self.textContent};}).duration(2990 * interval_time).attr("x", d => xScale(xValue(d)) + 10);}avg =(Number(currentData[0]["value"]) +Number(currentData[currentData.length - 1]["value"])) /2;var barExit = bar.exit().attr("fill-opacity", 1).transition().duration(2500 * interval_time);barExit.attr("transform", function (d) {if (always_up) {return "translate(0," + "-100" + ")";}if (Number(d.value) > avg && allow_up) {return "translate(0," + "-100" + ")";}return "translate(0," + "1000" + ")";}).remove().attr("fill-opacity", 0);barExit.select("rect").attr("fill-opacity", 0).attr("width", () => {if (always_up) return xScale(0);return xScale(currentData[currentData.length - 1]["value"]);});if (!long) {barExit.select(".value").attr("fill-opacity", 0).attr("x", () => {if (always_up) return xScale(0);return xScale(currentData[currentData.length - 1]["value"]);});}barExit.select(".barInfo").attr("fill-opacity", 0).attr("stroke-width", function (d) {return "0px";}).attr("x", () => {if (long) return 10;if (always_up) return xScale(0);return xScale(currentData[currentData.length - 1]["value"]);});barExit.select(".label").attr("fill-opacity", 0);if (config.use_img) {barExit.select("circle").attr("fill-opacity", 0);}}function change() {yScale.domain(currentData.map(d => d.name).reverse()).range([innerHeight, 0]);if (animation == "linear") {g.selectAll(".bar").data(currentData, function (d) {return d.name;}).transition("1").ease(d3.easeLinear).duration(baseTime * update_rate * interval_time).attr("transform", function (d) {return "translate(0," + yScale(yValue(d)) + ")";});} else {g.selectAll(".bar").data(currentData, function (d) {return d.name;}).transition("1").duration(baseTime * update_rate * interval_time).attr("transform", function (d) {return "translate(0," + yScale(yValue(d)) + ")";});}}var i = 0;var p = config.wait;var update_rate = config.update_rate;var inter = setInterval(function next() {// 空过p回合while (p) {p -= 1;return;}currentdate = time[i];getCurrentData(time[i]);i++;if (i >= time.length) {window.clearInterval(inter);}}, baseTime * interval_time);
}
效果:
近三十年各省GDP变化图
这篇关于数据可视化|基于Python数据清洗的Chart Race图的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!