Python數(shù)據(jù)可視化之Pyecharts使用詳解
1. 安裝Pyecharts
pip install pyecharts
2. 圖表基礎(chǔ)
2.1 主題風格
添加主題風格使用的是 InitOpts() 方法,
該方法的主要參數(shù)有:
| 參數(shù) | 描述 |
|---|---|
| width | 畫布寬度,要求字符串格式,如 width=“500px” |
| height | 畫布高度,要求字符串格式,如 width=“500px” |
| chart_id | 圖表ID,作為圖表的唯一標識。有多個圖表時用來區(qū)分不同的圖表 |
| page_title | 網(wǎng)頁標題,字符串格式 |
| theme | 圖表主題。由ThemeType模塊提供 |
| bg_color | 圖表背景顏色,字符串格式 |
可以選擇的風格有:

2.2 圖表標題
給圖表添加標題需要通過 set_global_options()方法 的 title_opts參數(shù),
該參數(shù)的值通過opts模塊的TitleOpts()方法生成,
且TitleOpts()方法主要參數(shù)語法如下:

2.3 圖例
設(shè)置圖例需要通過 set_global_opts()方法的 legend_opts參數(shù),
該參數(shù)的參數(shù)值參考options模塊的LegendOpts()方法。
LegendOpts() 方法的主要參數(shù)如下:

2.4 提示框
設(shè)置提示框主要是通過 set_global_opts()方法中的 tooltip_opts參數(shù)進行設(shè)置,
該參數(shù)的參數(shù)值參考options模塊的TooltipOpts()方法。
TooltipOpts()方法的主要參數(shù)如下:

2.5 視覺映射
視覺映射通過 set_global_opts()方法中的 visualmap_opts參數(shù)進行設(shè)置,
該參數(shù)的取值參考options模塊的VisualMapOpts()方法。
其主要參數(shù)如下:

2.6 工具箱
工具箱通過 set_global_opts()方法中的 toolbox_opts參數(shù)進行設(shè)置,
該參數(shù)的取值參考options模塊的ToolboxOpts()方法。
其主要參數(shù)如下:

2.7 區(qū)域縮放
區(qū)域縮放通過 set_global_opts()方法中的 datazoom_opts參數(shù)進行設(shè)置,
該參數(shù)的取值參考options模塊的DataZoomOpts()方法。
其主要參數(shù)如下:

3. 柱狀圖 Bar模塊
繪制柱狀圖通過Bar模塊來實現(xiàn),
該模塊的主要方法有:
| 主要方法 | 描述 |
|---|---|
| add_xaxis() | x軸數(shù)據(jù) |
| add_yaxis() | y軸數(shù)據(jù) |
| reversal_axis() | 翻轉(zhuǎn)x、y軸數(shù)據(jù) |
| add_dataset() | 原始數(shù)據(jù) |
下邊展示一個簡單的示例,先不使用過多復(fù)雜的樣式:
import numpy as np
from pyecharts.charts import Bar
from pyecharts import options as opts
from pyecharts.globals import ThemeType
# 生成數(shù)據(jù)
years = [2011, 2012, 2013, 2014, 2015]
y1 = [1, 3, 5, 7, 9]
y2 = [2, 4, 6, 4, 2]
y3 = [9, 7, 5, 3, 1]
y4 = list(np.random.randint(1, 10, 10))
bar = Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
# 為柱狀圖添加x軸和y軸數(shù)據(jù)
bar.add_xaxis(years)
bar.add_yaxis('A型', y1)
bar.add_yaxis('B型', y2)
bar.add_yaxis('C型', y3)
bar.add_yaxis('D型', y4)
# 渲染圖表到HTML文件,并保存在當前目錄下
bar.render("bar.html")
生成圖像效果如下:

這里有一個無法解釋的細節(jié),就是可以看到y(tǒng)4數(shù)據(jù),即D型,在圖像中沒有顯示出來。經(jīng)過小啾的反復(fù)嘗試,發(fā)現(xiàn)凡是使用隨機數(shù)產(chǎn)生的數(shù)據(jù)再轉(zhuǎn)化成列表,這部分隨機數(shù)不會被寫入到html文件中:

既然不會解釋,那就避免。
4. 折線圖/面積圖 Line模塊
Line模塊的主要方法有add_xaxis() 和 add_yaxis(),分別用來添加x軸數(shù)據(jù)和y軸數(shù)據(jù)。
add_yaxis()的主要參數(shù)如下:

4.1 折線圖
繪制折線圖時,x軸的數(shù)據(jù)必須是字符串,圖線方可正常顯示。
from pyecharts.charts import Line
from pyecharts import options as opts
from pyecharts.globals import ThemeType
# 準備數(shù)據(jù)
x = [2011, 2012, 2013, 2014, 2015]
x_data = [str(i) for i in x]
y1 = [1, 3, 2, 5, 8]
y2 = [2, 6, 5, 6, 7]
y3 = [5, 7, 4, 3, 1]
line = Line(init_opts=opts.InitOpts(theme=ThemeType.ESSOS))
line.add_xaxis(xaxis_data=x_data)
line.add_yaxis(series_name="A類", y_axis=y1)
line.add_yaxis(series_name="B類", y_axis=y2)
line.add_yaxis(series_name="C類", y_axis=y3)
line.render("line.html")
生成圖像效果如下:

4.2 面積圖
繪制面積圖時需要在add_yaxis()方法中指定areastyle_opts參數(shù)。其值由options模塊的AreaStyleOpts()方法提供。
from pyecharts.charts import Line
from pyecharts import options as opts
from pyecharts.globals import ThemeType
x = [2011, 2012, 2013, 2014, 2015]
x_data = [str(i) for i in x]
y1 = [2, 5, 6, 8, 9]
y2 = [1, 4, 5, 4, 7]
y3 = [1, 3, 4, 6, 6]
line = Line(init_opts=opts.InitOpts(theme=ThemeType.WONDERLAND))
line.add_xaxis(xaxis_data=x_data)
line.add_yaxis(series_name="A類", y_axis=y1, areastyle_opts=opts.AreaStyleOpts(opacity=1))
line.add_yaxis(series_name="B類", y_axis=y2, areastyle_opts=opts.AreaStyleOpts(opacity=1))
line.add_yaxis(series_name="C類", y_axis=y3, areastyle_opts=opts.AreaStyleOpts(opacity=1))
line.render("line2.html")
圖像效果如下:

5.餅形圖
5.1 餅形圖
繪制餅形圖使用的是Pie模塊,該模塊中需要使用的主要方法是add()方法
該方法主要參數(shù)如下:
| 主要參數(shù) | 描述 |
|---|---|
| series_name | 系列名稱。用于提示文本和圖例標簽。 |
| data_pair | 數(shù)據(jù)項,格式為形如[(key1,value1),(key2,value2)] |
| color | 系列標簽的顏色。 |
| radius | 餅圖的半徑。默認設(shè)成百分比形式,默認是相對于容器的高和寬中較小的一方的一半 |
| rosetype | 是否展開為南丁格爾玫瑰圖,可以取的值有radius貨area,radius表示通過扇區(qū)圓心角展現(xiàn)數(shù)據(jù)的大小,即默認的扇形圖;area表示所有扇區(qū)的圓心角的角度相同,通過半徑來展現(xiàn)數(shù)據(jù)大小 |
from pyecharts.charts import Pie
from pyecharts import options as opts
from pyecharts.globals import ThemeType
x_data = ['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF']
y_data = [200, 200, 100, 400, 500, 600]
# 將數(shù)據(jù)轉(zhuǎn)換為目標格式
data = [list(z) for z in zip(x_data, y_data)]
# 數(shù)據(jù)排序
data.sort(key=lambda x: x[1])
pie = Pie(init_opts=opts.InitOpts(theme=ThemeType.MACARONS))
pie.add(
series_name="類別", # 序列名稱
data_pair=data, # 數(shù)據(jù)
)
pie.set_global_opts(
# 餅形圖標題
title_opts=opts.TitleOpts(
title="各類別數(shù)量分析",
pos_left="center"),
# 不顯示圖例
legend_opts=opts.LegendOpts(is_show=False),
)
pie.set_series_opts(
# 序列標簽
label_opts=opts.LabelOpts(),
)
pie.render("pie.html")
圖像效果如下:

5.2 南丁格爾玫瑰圖
from pyecharts.charts import Pie
from pyecharts import options as opts
from pyecharts.globals import ThemeType
x_data = ['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF', 'GGG', 'HHH', 'III', 'JJJ', 'KKK', 'LLL', 'MMM', 'NNN', 'OOO']
y_data = [200, 100, 400, 50, 600, 300, 500, 700, 800, 900, 1000, 1100, 1200, 1300, 1500]
# 將數(shù)據(jù)轉(zhuǎn)換為目標格式
data = [list(z) for z in zip(x_data, y_data)]
# 數(shù)據(jù)排序
data.sort(key=lambda x: x[1])
# 創(chuàng)建餅形圖并設(shè)置畫布大小
pie = Pie(init_opts=opts.InitOpts(theme=ThemeType.ROMANTIC, width='300px', height='400px'))
# 為餅形圖添加數(shù)據(jù)
pie.add(
series_name="類別",
data_pair=data,
radius=["8%", "160%"], # 內(nèi)外半徑
center=["65%", "65%"], # 位置
rosetype='area', # 玫瑰圖,圓心角相同,按半徑大小繪制
color='auto' # 顏色自動漸變
)
pie.set_global_opts(
# 不顯示圖例
legend_opts=opts.LegendOpts(is_show=False),
# 視覺映射
visualmap_opts=opts.VisualMapOpts(is_show=False,
min_=100, # 顏色條最小值
max_=450000, # 顏色條最大值
)
)
pie.set_series_opts(
# 序列標簽
label_opts=opts.LabelOpts(position='inside', # 標簽位置
rotate=45,
font_size=8) # 字體大小
)
pie.render("pie2.html")
圖像效果如下:

6. 箱線圖 Boxplot模塊
繪制箱線圖使用的是Boxplot類。
這里有一個細節(jié),準備y軸數(shù)據(jù)y_data時需要在列表外再套一層列表,否則圖線不會被顯示。
繪制箱線圖使用的是Boxplot模塊,
主要的方法有
add_xaxis()和add_yaxis()
from pyecharts.charts import Boxplot
from pyecharts.globals import ThemeType
from pyecharts import options as opts
y_data = [[5, 20, 22, 21, 23, 26, 25, 24, 28, 26, 29, 30, 50, 61]]
boxplot = Boxplot(init_opts=opts.InitOpts(theme=ThemeType.INFOGRAPHIC))
boxplot.add_xaxis([""])
boxplot.add_yaxis('', y_axis=boxplot.prepare_data(y_data))
boxplot.render("boxplot.html")
圖像效果如下:

7. 漣漪特效散點圖 EffectScatter模塊
繪制漣漪圖使用的是EffectScatter模塊,代碼示例如下:
from pyecharts.charts import EffectScatter
from pyecharts import options as opts
from pyecharts.globals import ThemeType
x = [2011, 2012, 2013, 2014, 2015]
x_data = [str(i) for i in x]
y1 = [1, 3, 2, 5, 8]
y2 = [2, 6, 5, 6, 7]
y3 = [5, 7, 4, 3, 1]
scatter = EffectScatter(init_opts=opts.InitOpts(theme=ThemeType.VINTAGE))
scatter.add_xaxis(x_data)
scatter.add_yaxis("", y1)
scatter.add_yaxis("", y2)
scatter.add_yaxis("", y3)
# 渲染圖表到HTML文件,存放在程序所在目錄下
scatter.render("EffectScatter.html")
圖像效果如下:

8. 詞云圖 WordCloud模塊
繪制詞云圖使用的是WordCloud模塊,
主要的方法有add()方法。
add()方法的主要參數(shù)如下:
add()方法主要的參數(shù)有

準備一個txt文件(001.txt),文本內(nèi)容以《蘭亭集序》為例:
永和九年,歲在癸丑,暮春之初,會于會稽山陰之蘭亭,修禊事也。群賢畢至,少長咸集。此地有崇山峻嶺,茂林修竹,又有清流激湍,映帶左右,引以為流觴曲水,列坐其次。雖無絲竹管弦之盛,一觴一詠,亦足以暢敘幽情。
是日也,天朗氣清,惠風和暢。仰觀宇宙之大,俯察品類之盛,所以游目騁懷,足以極視聽之娛,信可樂也。
夫人之相與,俯仰一世?;蛉≈T懷抱,悟言一室之內(nèi);或因寄所托,放浪形骸之外。雖趣舍萬殊,靜躁不同,當其欣于所遇,暫得于己,快然自足,不知老之將至;及其所之既倦,情隨事遷,感慨系之矣。向之所欣,俯仰之間,已為陳跡,猶不能不以之興懷,況修短隨化,終期于盡!古人云:“死生亦大矣。”豈不痛哉!
每覽昔人興感之由,若合一契,未嘗不臨文嗟悼,不能喻之于懷。固知一死生為虛誕,齊彭殤為妄作。后之視今,亦猶今之視昔,悲夫!故列敘時人,錄其所述,雖世殊事異,所以興懷,其致一也。后之覽者,亦將有感于斯文。
代碼示例如下:
from pyecharts.charts import WordCloud
from jieba import analyse
# 基于TextRank算法從文本中提取關(guān)鍵詞
textrank = analyse.textrank
text = open('001.txt', 'r', encoding='UTF-8').read()
keywords = textrank(text, topK=30)
list1 = []
tup1 = ()
# 關(guān)鍵詞列表
for keyword, weight in textrank(text, topK=30, withWeight=True):
# print('%s %s' % (keyword, weight))
tup1 = (keyword, weight) # 關(guān)鍵詞權(quán)重
list1.append(tup1) # 添加到列表中
# 繪制詞云圖
mywordcloud = WordCloud()
mywordcloud.add('', list1, word_size_range=[20, 100])
mywordcloud.render('wordclound.html')
詞云圖效果如下:

9. 熱力圖 HeatMap模塊
繪制熱力圖使用的是HeatMap模塊。
下邊以雙色球案例為例,數(shù)據(jù)使用生成的隨機數(shù),繪制出熱力圖:
import pyecharts.options as opts
from pyecharts.charts import HeatMap
import pandas as pd
import numpy as np
# 創(chuàng)建一個33行7列的DataFrame,數(shù)據(jù)使用隨機數(shù)生成。每個數(shù)據(jù)表示該位置上該數(shù)字出現(xiàn)的次數(shù)
s1 = np.random.randint(0, 200, 33)
s2 = np.random.randint(0, 200, 33)
s3 = np.random.randint(0, 200, 33)
s4 = np.random.randint(0, 200, 33)
s5 = np.random.randint(0, 200, 33)
s6 = np.random.randint(0, 200, 33)
s7 = np.random.randint(0, 200, 33)
data = pd.DataFrame(
{'位置一': s1,
'位置二': s2,
'位置三': s3,
'位置四': s4,
'位置五': s5,
'位置六': s6,
'位置七': s7
},
index=range(1, 34)
)
# 數(shù)據(jù)轉(zhuǎn)換為HeatMap支持的列表格式
value1 = []
for i in range(7):
for j in range(33):
value1.append([i, j, int(data.iloc[j, i])])
# 繪制熱力圖
x = data.columns
heatmap=HeatMap(init_opts=opts.InitOpts(width='600px' ,height='650px'))
heatmap.add_xaxis(x)
heatmap.add_yaxis("aa", list(data.index), value=value1, # y軸數(shù)據(jù)
# y軸標簽
label_opts=opts.LabelOpts(is_show=True, color='white', position="center"))
heatmap.set_global_opts(title_opts=opts.TitleOpts(title="雙色球中獎號碼熱力圖", pos_left="center"),
legend_opts=opts.LegendOpts(is_show=False), # 不顯示圖例
# 坐標軸配置項
xaxis_opts=opts.AxisOpts(
type_="category", # 類目軸
# 分隔區(qū)域配置項
splitarea_opts=opts.SplitAreaOpts(
is_show=True, # 區(qū)域填充樣式
areastyle_opts=opts.AreaStyleOpts(opacity=1)
),
),
# 坐標軸配置項
yaxis_opts=opts.AxisOpts(
type_="category", # 類目軸
# 分隔區(qū)域配置項
splitarea_opts=opts.SplitAreaOpts(
is_show=True,
# 區(qū)域填充樣式
areastyle_opts=opts.AreaStyleOpts(opacity=1)
),
),
# 視覺映射配置項
visualmap_opts=opts.VisualMapOpts(is_piecewise=True, # 分段顯示
min_=1, max_=170, # 最小值、最大值
orient='horizontal', # 水平方向
pos_left="center") # 居中
)
heatmap.render("heatmap.html")
熱力圖效果如下:

10. 水球圖 Liquid模塊
繪制水球圖使用的是Liquid模塊。
from pyecharts.charts import Liquid
liquid = Liquid()
liquid.add('', [0.39])
liquid.render("liquid.html")
水球圖效果如下:

11. 日歷圖 Calendar模塊
繪制日歷圖使用的是Calendar模塊
主要使用的方法是add()方法
import pandas as pd
import numpy as np
from pyecharts import options as opts
from pyecharts.charts import Calendar
data = list(np.random.random(30))
# 求最大值和最小值
mymax = round(max(data), 2)
mymin = round(min(data), 2)
# 生成日期
index = pd.date_range('20220401', '20220430')
# 合并列表
data_list = list(zip(index, data))
# 生成日歷圖
calendar = Calendar()
calendar.add("",
data_list,
calendar_opts=opts.CalendarOpts(range_=['2022-04-01', '2022-04-30']))
calendar.set_global_opts(
title_opts=opts.TitleOpts(title="2022年4月某指標情況", pos_left='center'),
visualmap_opts=opts.VisualMapOpts(
max_=mymax,
min_=mymin+0.1,
orient="horizontal",
is_piecewise=True,
pos_top="230px",
pos_left="70px",
),
)
calendar.render("calendar.html")日歷圖效果如下:

以上就是Python數(shù)據(jù)可視化之Pyecharts使用詳解的詳細內(nèi)容,更多關(guān)于Python Pyecharts的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python集成測試提高軟件質(zhì)量關(guān)鍵步驟探究
Python是一門強大的編程語言,提供了眾多工具和庫,用于執(zhí)行高效的集成測試,本文將深入介紹Python集成測試的概念、方法和最佳實踐,并通過豐富的示例代碼演示如何提高軟件質(zhì)量和減少潛在的缺陷2024-01-01
關(guān)于tf.TFRecordReader()函數(shù)的用法解析
今天小編就為大家分享一篇關(guān)于tf.TFRecordReader()函數(shù)的用法解析,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
基于Python中單例模式的幾種實現(xiàn)方式及優(yōu)化詳解
下面小編就為大家分享一篇基于Python中單例模式的幾種實現(xiàn)方式及優(yōu)化詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01
關(guān)于Python面向?qū)ο缶幊痰闹R點總結(jié)
Python從設(shè)計之初就已經(jīng)是一門面向?qū)ο蟮恼Z言,正因為如此,在Python中創(chuàng)建一個類和對象是很容易的。下面這篇文章將詳細給大家介紹關(guān)于Python面向?qū)ο缶幊痰闹R點,需要的朋友可以參考借鑒,下面來一起看看吧。2017-02-02

