Python使用Matplotlib繪制專業(yè)柱狀圖的完整指南
1. 基礎(chǔ)柱狀圖繪制
import matplotlib.pyplot as plt import numpy as np # 數(shù)據(jù)準(zhǔn)備 categories = ['蘋果', '香蕉', '橙子', '葡萄', '芒果'] sales_volume = [85, 67, 92, 45, 71] # 創(chuàng)建圖表 plt.figure(figsize=(10, 6)) # 設(shè)置畫(huà)布大小 plt.bar(categories, sales_volume, color='skyblue', edgecolor='black') # 添加標(biāo)簽和標(biāo)題 plt.title('水果銷售情況', fontsize=14, fontweight='bold') plt.xlabel('水果種類', fontsize=12) plt.ylabel('銷售量(千克)', fontsize=12) plt.grid(axis='y', linestyle='--', alpha=0.7) # 添加橫向網(wǎng)格線 # 顯示圖表 plt.tight_layout() plt.show()
2. 自定義樣式進(jìn)階
# 使用seaborn樣式 plt.style.use('seaborn-v0_8-darkgrid') # 數(shù)據(jù)準(zhǔn)備 months = ['1月', '2月', '3月', '4月', '5月'] revenue = [125, 142, 98, 167, 210] cost = [75, 82, 65, 92, 110] # 創(chuàng)建子圖 fig, ax = plt.subplots(figsize=(12, 7)) # 繪制柱狀圖(設(shè)置寬度和位置) bar_width = 0.35 x_indexes = np.arange(len(months)) ax.bar(x_indexes - bar_width/2, revenue, width=bar_width, label='收入', color='#2ecc71', edgecolor='black') ax.bar(x_indexes + bar_width/2, cost, width=bar_width, label='成本', color='#e74c3c', edgecolor='black') # 添加數(shù)據(jù)標(biāo)簽 for i, v in enumerate(revenue): ax.text(i - bar_width/2, v + 5, str(v), ha='center', fontsize=10) for i, v in enumerate(cost): ax.text(i + bar_width/2, v + 5, str(v), ha='center', fontsize=10) # 設(shè)置圖表元素 ax.set_title('月度收入與成本對(duì)比', fontsize=16, pad=20) ax.set_xlabel('月份', fontsize=12) ax.set_ylabel('金額(萬(wàn)元)', fontsize=12) ax.set_xticks(x_indexes) ax.set_xticklabels(months) ax.legend(frameon=True, shadow=True) # 添加橫向參考線 ax.axhline(y=150, color='gray', linestyle='--', alpha=0.5) # 設(shè)置坐標(biāo)軸范圍 ax.set_ylim(0, 250) # 添加腳注 plt.figtext(0.5, 0.01, '數(shù)據(jù)來(lái)源: 公司財(cái)務(wù)報(bào)告2023', ha='center', fontsize=9, color='gray') plt.tight_layout() plt.savefig('business_analysis.png', dpi=300) # 保存高清圖片 plt.show()
3. 水平柱狀圖
# 數(shù)據(jù)準(zhǔn)備 countries = ['美國(guó)', '中國(guó)', '日本', '德國(guó)', '英國(guó)'] gdp_growth = [2.3, 5.2, 1.1, 1.8, -0.3] # 創(chuàng)建圖表 plt.figure(figsize=(10, 6)) # 水平柱狀圖(負(fù)值用不同顏色) colors = ['#3498db' if x >= 0 else '#e74c3c' for x in gdp_growth] plt.barh(countries, gdp_growth, color=colors, edgecolor='black') # 添加數(shù)據(jù)標(biāo)簽 for i, v in enumerate(gdp_growth): plt.text(v, i, f'{v}%', va='center', color='black' if abs(v) < 2 else 'white', fontweight='bold') # 設(shè)置圖表元素 plt.title('2023年GDP增長(zhǎng)率對(duì)比', fontsize=14) plt.xlabel('增長(zhǎng)率(%)') plt.xlim(-1, 6) plt.grid(axis='x', alpha=0.5) plt.tight_layout() plt.show()
4. 堆疊柱狀圖
# 數(shù)據(jù)準(zhǔn)備 quarters = ['第一季度', '第二季度', '第三季度', '第四季度'] online_sales = [120, 145, 180, 210] offline_sales = [80, 95, 110, 130] # 創(chuàng)建圖表 plt.figure(figsize=(10, 6)) # 繪制堆疊柱狀圖 plt.bar(quarters, online_sales, label='線上銷售', color='#9b59b6') plt.bar(quarters, offline_sales, bottom=online_sales, label='線下銷售', color='#3498db') # 添加總銷售額標(biāo)簽 total_sales = [online_sales[i] + offline_sales[i] for i in range(len(quarters))] for i, total in enumerate(total_sales): plt.text(i, total + 10, f'總銷售額: {total}', ha='center', fontsize=9) # 設(shè)置圖表元素 plt.title('線上線下銷售渠道對(duì)比', fontsize=14) plt.ylabel('銷售額(萬(wàn)元)') plt.legend(loc='upper left') plt.ylim(0, 400) plt.tight_layout() plt.show()
5. 專業(yè)技巧與最佳實(shí)踐
配色方案:
- 使用漸變色表示數(shù)值大小
- 重要數(shù)據(jù)使用突出顏色
- 保持整體配色協(xié)調(diào)(可使用coolwarm、viridis等內(nèi)置色彩映射)
布局優(yōu)化:
plt.figure(figsize=(12, 7), dpi=100) # 高清輸出 plt.subplots_adjust(left=0.1, right=0.95, top=0.9, bottom=0.15) # 自定義邊距
高級(jí)標(biāo)注:
# 添加顯著性標(biāo)記 plt.annotate('創(chuàng)紀(jì)錄銷售', xy=(3, 340), xytext=(3.5, 320), arrowprops=dict(arrowstyle='->', color='red'), fontsize=10, color='red')
3D柱狀圖:
from mpl_toolkits.mplot3d import Axes3D fig = plt.figure(figsize=(10, 8)) ax = fig.add_subplot(111, projection='3d') # 生成3D柱狀圖數(shù)據(jù) xpos = [1, 2, 3, 4] ypos = [1, 2, 3] zpos = np.zeros(4) dx = np.ones(4) * 0.5 dy = np.ones(4) * 0.5 dz = [10, 15, 12, 8] ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='#1abc9c', shade=True) ax.set_title('3D銷售數(shù)據(jù)展示', fontsize=14) ax.set_xlabel('區(qū)域') ax.set_ylabel('季度') ax.set_zlabel('銷售額')
6. 常見(jiàn)問(wèn)題解決
中文顯示問(wèn)題:
plt.rcParams['font.sans-serif'] = ['SimHei'] # 解決中文亂碼 plt.rcParams['axes.unicode_minus'] = False # 解決負(fù)號(hào)顯示問(wèn)題
柱狀圖重疊:
- 調(diào)整
bar_width
參數(shù) - 使用
x_indexes
控制位置 - 添加透明度
alpha=0.8
大數(shù)據(jù)集優(yōu)化:
- 使用
ax.bar()
替代plt.bar()
提高性能 - 對(duì)于超過(guò)50個(gè)類別的數(shù)據(jù),考慮使用水平柱狀圖
通過(guò)掌握這些技巧,你可以創(chuàng)建出適用于商業(yè)報(bào)告、學(xué)術(shù)論文和數(shù)據(jù)儀表盤的專業(yè)級(jí)柱狀圖。Matplotlib的強(qiáng)大功能結(jié)合Python的數(shù)據(jù)處理能力,使數(shù)據(jù)可視化變得既靈活又高效!
總結(jié)與擴(kuò)展
本文從基礎(chǔ)柱狀圖到多組對(duì)比、堆疊柱狀圖,再到結(jié)合實(shí)際數(shù)據(jù)的繪制,覆蓋了柱狀圖的核心用法。關(guān)鍵技巧總結(jié)如下:
- 單組數(shù)據(jù)用
plt.bar(x, height)
,多組數(shù)據(jù)需調(diào)整x
位置避免重疊; - 堆疊柱狀圖通過(guò)
bottom
參數(shù)實(shí)現(xiàn),適合展示部分與整體關(guān)系; - 樣式美化的核心是:清晰的標(biāo)題 / 標(biāo)簽、合理的顏色搭配、輔助網(wǎng)格線和數(shù)據(jù)標(biāo)簽;
- 結(jié)合
pandas
可高效處理實(shí)際業(yè)務(wù)數(shù)據(jù),降低代碼復(fù)雜度。
實(shí)際應(yīng)用中,可根據(jù)需求進(jìn)一步探索動(dòng)態(tài)柱狀圖(如plotly
庫(kù))、3D 柱狀圖等擴(kuò)展形式,讓數(shù)據(jù)可視化更具表現(xiàn)力。
通過(guò)不斷調(diào)整參數(shù)、嘗試不同樣式,你可以繪制出既美觀又實(shí)用的柱狀圖,讓數(shù)據(jù)傳遞更高效的信息。
以上就是Python使用Matplotlib繪制專業(yè)柱狀圖的完整指南的詳細(xì)內(nèi)容,更多關(guān)于Python Matplotlib繪制柱狀圖的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python處理JSON數(shù)據(jù)并導(dǎo)入Neo4j數(shù)據(jù)庫(kù)
在數(shù)據(jù)處理和分析中,JSON是一種常見(jiàn)的數(shù)據(jù)格式,Neo4j是一個(gè)高性能的圖數(shù)據(jù)庫(kù),能夠存儲(chǔ)和查詢復(fù)雜的網(wǎng)絡(luò)關(guān)系,下面我們就來(lái)看看Python如何處理JSON數(shù)據(jù)并導(dǎo)入Neo4j數(shù)據(jù)庫(kù)吧2024-11-11基于wxPython的GUI實(shí)現(xiàn)輸入對(duì)話框(2)
這篇文章主要為大家詳細(xì)介紹了基于wxPython的GUI實(shí)現(xiàn)輸入對(duì)話框的第二篇,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02解決django前后端分離csrf驗(yàn)證的問(wèn)題
今天小編就為大家分享一篇解決django前后端分離csrf驗(yàn)證的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-02-02Python輕松獲取網(wǎng)絡(luò)時(shí)間和本地時(shí)間技巧揭秘
這篇文章主要為大家介紹了Python輕松獲取網(wǎng)絡(luò)時(shí)間和本地時(shí)間技巧揭秘,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01Python庫(kù)textract提取各種文檔類型中文本數(shù)據(jù)
Python的textract庫(kù)是一個(gè)強(qiáng)大的工具,它可以從各種文檔類型中提取文本數(shù)據(jù),無(wú)論是PDF、Word文檔、圖片還是其他格式的文件,textract都可以輕松地將文本提取出來(lái),本文將詳細(xì)介紹textract的功能和用法,并提供豐富的示例代碼來(lái)幫助大家深入了解2024-01-01