對(duì)比Excel,用Python繪制柱狀圖時(shí)添加Table數(shù)據(jù)表
本文轉(zhuǎn)載自微信公眾號(hào)「可以叫我才哥」,作者才哥。轉(zhuǎn)載本文請(qǐng)聯(lián)系可以叫我才哥公眾號(hào)。
大家好,我是才哥。
最近在做數(shù)據(jù)可視化的時(shí)候,希望在圖上同時(shí)顯示數(shù)據(jù)表。關(guān)于這個(gè)需求,用excel可以比較方便,直接快速布局中選擇布局5即可。那么,如果我們想用python也來完成這項(xiàng)任務(wù),可以怎么做呢?
期望效果預(yù)覽:
excel作圖效果
1. Excel簡(jiǎn)單繪制
就很簡(jiǎn)單了,直接選中數(shù)據(jù)插入柱狀圖,然后在圖表工具-設(shè)計(jì)-快速布局中選擇相應(yīng)的布局即可。
案例數(shù)據(jù)及效果
excel圖表設(shè)計(jì)->快速布局—>布局5
2. Python繪制
那這里我們用到的是matplotlib,bar和table。
將圖表元素進(jìn)行拆解,可以分為柱狀圖和數(shù)據(jù)表,剛好matplotlib提供了對(duì)應(yīng)的接口。
2.1 柱狀圖繪制
先繪制柱狀圖,案例中是兩組數(shù)據(jù),所以是組合柱狀圖。在本次繪制中,有以下幾個(gè)知識(shí)點(diǎn),可以記一記:
- 設(shè)置標(biāo)題時(shí)的位置(用參數(shù)x,y指定)
- 設(shè)置坐標(biāo)軸標(biāo)題時(shí)用參數(shù)rotation旋轉(zhuǎn)方向
- 設(shè)置坐標(biāo)軸區(qū)間范圍
- 顯示數(shù)據(jù)標(biāo)簽(用ax.bar_label方法)
- import numpy as np
- import matplotlib.pyplot as plt
- # 中文及負(fù)數(shù)顯示
- plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
- plt.rcParams['axes.unicode_minus'] = False
- # 創(chuàng)建畫布
- fig, ax = plt.subplots(figsize=(10, 4), dpi=100)
- # 案例數(shù)據(jù)
- data = [[150, 200, -50, -100, -75],
- [300, 125, -80, 75, -100],
- ]
- # 列與行
- columns = ('周一', '周二', '周三', '周四', '周五')
- rows = ['才哥', '楠楠']
- # 作圖參數(shù)
- index = np.arange(len(columns))-0.1
- bar_width = 0.4
- # 設(shè)置柱狀圖顏色
- colors = ['turquoise', 'coral']
- # 柱狀圖
- bar1 = plt.bar(index, data[0],
- bar_width, color=colors[0], edgecolor='grey')
- bar2 = plt.bar(index+bar_width, data[1],
- bar_width, color=colors[1], edgecolor='grey')
- # 設(shè)置標(biāo)題
- ax.set_title('工作日收益情況', fontsize=16, y=1.1,x=0.44)
- # 設(shè)置坐標(biāo)軸標(biāo)題
- ax.set_ylabel("元", fontsize=12, color='black', alpha=0.7, rotation=360)
- # 設(shè)置Y軸區(qū)間
- ax.set_ylim(-150, 350)
- # 顯示數(shù)據(jù)標(biāo)簽
- ax.bar_label(bar1, label_type='edge')
- ax.bar_label(bar2, label_type='edge')
- # x,y軸刻度不顯示
- ax.tick_params(axis=u'both', which=u'both', length=0)
- # x軸刻度及刻度值不顯示
- plt.xticks([])
輸出如下:
組合柱狀圖
2.2. 圖表table繪制
先看看圖表table的繪制,我們拿案例數(shù)據(jù)來單獨(dú)繪制看看:
- # 創(chuàng)建畫布
- fig, ax = plt.subplots(figsize=(10, 4), dpi=100)
- # table圖表
- the_table = plt.table(cellText=data,
- rowLabels=rows,rowColours=colors,
- colLabels=columns, cellLoc='center', loc="bottom",
- bbox=[0, -0.4, 1, 0.24]
- )
輸出如下:
table
關(guān)于 plt.table的參數(shù)介紹如下:
cellText:表格單元格文本,字符串中的換行符暫不支持,可能導(dǎo)致文本超出單元格邊界
cellColours:表格單元格背景色
cellLoc:表格單元格文本的對(duì)齊方式,取值范圍為{'left', 'center', 'right'},默認(rèn)值為'right'
colWidths:表格單元格寬度
rowLabels:表格行表頭文本
rowColours:表格行表頭背景色
rowLoc:表格行表頭文本的對(duì)齊方式,取值范圍為{'full', 'left', 'right'},默認(rèn)值為'left'
colLabels:表格列表頭文本
colColours:表格列表頭背景色
colLoc:表格列表頭文本的對(duì)齊方式,取值范圍為{'full', 'left', 'right'},默認(rèn)值為'left'
loc:?jiǎn)卧裣鄬?duì)于子圖的位置
bbox:繪制表格的邊界框
最后,我們需要做的就是將上述兩個(gè)圖進(jìn)行組合,組合過程中可能需要做一些格式微調(diào)。
2.3. 組合
在本次案例中,對(duì)組合圖需求有以下幾點(diǎn):
- 柱狀圖邊框不顯示
- 圖表table中列名高度需要高一些,單元格的高度要低一些
- 圖例位置需要和對(duì)應(yīng)行一致
為了實(shí)現(xiàn)上訴需求,我們可以通過以下方式來處理:
- # 設(shè)置單元格高度
- cellDict = the_table.get_celld()
- for i in range(0, len(columns)):
- cellDict[(0, i)].set_height(0.6)
- for j in range(1, len(rows)+1):
- cellDict[(j, i)].set_height(0.4)
- # 設(shè)置圖表table中行名單元格的高度
- cellDict[(1, -1)].set_height(0.4)
- cellDict[(2, -1)].set_height(0.4)
- # 設(shè)置圖表table單元格文本字體
- the_table.auto_set_font_size(False)
- the_table.set_fontsize(10)
- # 設(shè)置圖表table單元格邊框
- for key, cell in the_table.get_celld().items():
- cell.set_linewidth(0.6)
- # 邊框隱藏
- ax.spines['top'].set_visible(False)
- ax.spines['right'].set_visible(False)
- ax.spines['bottom'].set_visible(False)
- ax.spines['left'].set_visible(False)
- name = ['', '']
- # 設(shè)置圖例的位置
- ax.legend(name, handlelength=0.7, labelspacing=0.6,
- bbox_to_anchor=(-0.1, -0.23),
- loc='upper left', frameon=False)
最終,我們可以得到比較滿意的效果:
最終效果
以上就是本次全部?jī)?nèi)容,大家可以修改參數(shù)多試試以熟悉掌握。