原始數(shù)據(jù)都一樣,為啥Pyecharts做出來的圖一個(gè)是彩色的,另一個(gè)是黑白的?
大家好,我是Python進(jìn)階者。
前言
前幾天在鉑金交流群里,有個(gè)叫【小朋友】的粉絲在Python交流群里問了一道關(guān)于Pyecharts可視化的問題,初步一看覺得很簡單,實(shí)際上確實(shí)是有難度的,問題如下。
乍一看,這個(gè)問題不知道他在說什么,看完代碼之后,我才明白他的意思。
一、思路
下面是他的代碼,首先是讀取excel文件,之后他用了兩種方法生成數(shù)據(jù),一個(gè)是datas,另外一個(gè)是datas2,這兩個(gè)數(shù)據(jù),最后通過比對(duì),發(fā)現(xiàn)竟然是一樣的,數(shù)據(jù)也都相等,但是唯獨(dú)最后生成的html動(dòng)圖,有點(diǎn)不一樣。
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Map
import operator as op
import time
df_tb = pd.read_excel('./data.xlsx')
locations = [location for location in df_tb['地區(qū)']]
values = [value for value in df_tb['2016年']]
datas = list(zip(locations, values))
print(datas)
for data in datas:
print(data)
# print(type(data))
print(type(datas))
# print("==============================")
# def func(m):
# a = []
# for i in range(0, 35):
# b = (df_tb['地區(qū)'][i], df_tb[m][i])
# a.append(b)
# return a
# datas2 = func('2016年')
# for data in datas2:
# print(data)
# print(type(data))
# print(datas2)
# print(type(datas2))
map = (
Map().
add('gdp', [location for location in datas], 'china')
# .add('gdp', [list(location) for location in datas], 'china')
.set_global_opts(
title_opts=opts.TitleOpts(title='各省貧困縣分布圖'),
visualmap_opts=opts.VisualMapOpts(max_=150)
)
)
map.render('各省貧困縣分布圖.html')
# print(op.eq(datas, func('2016年')))
下圖是datas生成的html動(dòng)圖,是有顏色的,而且有數(shù)據(jù)顯示,如下圖所示。
下圖是datas2生成的html動(dòng)圖,是無顏色的,而且無數(shù)據(jù)顯示,如下圖所示。
這就確實(shí)很奇怪了,明明數(shù)據(jù)都一樣,為啥最后生成的圖效果差別就這么大呢?不細(xì)心一點(diǎn),還真的難以發(fā)現(xiàn)呢!
二、解決方法
其實(shí)一開始我看到這里,也是覺得非常的奇怪,都沒有任何的想法,后來我想了下,竟然地圖上的省位都可以顯示出來,只是數(shù)據(jù)方面呈現(xiàn)有問題,那么說明肯定是數(shù)據(jù)的問題。從這個(gè)思路出發(fā),我很快就找到了問題所在。依次遍歷datas和datas2數(shù)據(jù),查看數(shù)據(jù)的type,很快就看到了問題,如下圖所示:
可以清晰的看到datas列表里邊的數(shù)字的類型是int類型,而datas2列表里邊的數(shù)字的類型是numpy.int64類型,而numpy.int64類型在html中是顯示不出來的,因此問題就水落石出了。只需要在函數(shù)處理的時(shí)候?qū)umpy.int64類型來個(gè)強(qiáng)轉(zhuǎn)變?yōu)閕nt類型,問題就迎刃而解了。只需要將func()函數(shù)中的代碼替換成下面這個(gè)就可以了:
def func(m):
a = []
for i in range(0, 35):
b = (df_tb['地區(qū)'][i], int(df_tb[m][i]))
a.append(b)
return a
之后再次運(yùn)行程序,可以看到數(shù)值便可以正常顯示出來了,如下圖所示。
三、總結(jié)
我是Python進(jìn)階者。本文基于粉絲針對(duì)Pyecharts可視化過程中的提問,給出了一個(gè)滿意的解決方案,達(dá)到了粉絲的要求。