Python使用Chartify庫(kù)進(jìn)行數(shù)據(jù)分析繪制詳解
前言
數(shù)據(jù)可視化這事兒,搞過(guò)的都知道有多費(fèi)勁。
用matplotlib畫個(gè)圖要調(diào)半天參數(shù),才能讓圖表看起來(lái)稍微順眼一點(diǎn);seaborn雖然畫出來(lái)的圖確實(shí)好看,但是配置項(xiàng)太多,記不住,每次用都要查文檔。
直到遇見(jiàn)了Chartify這個(gè)寶貝疙瘩,簡(jiǎn)直就是救命稻草?。∵@玩意兒是Spotify開(kāi)源的,我愿稱之為“懶人神器”。
它提供了簡(jiǎn)潔易用的API,讓我們能夠快速地繪制出美觀且專業(yè)的圖表,無(wú)需像使用matplotlib和seaborn那樣花費(fèi)大量時(shí)間去調(diào)整各種復(fù)雜的參數(shù),大大提高了數(shù)據(jù)可視化的效率,讓數(shù)據(jù)可視化變得輕松又愉快。
為啥要用Chartify
說(shuō)實(shí)話,我一開(kāi)始也不信這個(gè)庫(kù)能有多厲害。
畢竟市面上的可視化庫(kù)多如牛毛,matplotlib、seaborn、plotly哪個(gè)不是響當(dāng)當(dāng)?shù)拿郑?/p>
但是實(shí)際用下來(lái)才發(fā)現(xiàn),這些傳統(tǒng)庫(kù)都有一個(gè)共同的痛點(diǎn):配置太復(fù)雜。
拿matplotlib來(lái)說(shuō),畫個(gè)簡(jiǎn)單的折線圖都得寫好幾行代碼:
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) y = np.sin(x) plt.figure(figsize=(10, 6)) plt.plot(x, y) plt.title('Sin Wave') plt.xlabel('X axis') plt.ylabel('Y axis') plt.grid(True) plt.show()
這還只是最基礎(chǔ)的配置,要是想調(diào)整字體、顏色、樣式,那代碼量能翻好幾倍。
而用Chartify,同樣的圖只需要幾行代碼:
import chartify ch = chartify.Chart() ch.plot.line( data_frame=pd.DataFrame({'x': x, 'y': y}), x_column='x', y_column='y' ) ch.show()
看到差別了吧?這就是為啥我說(shuō)它能提升13倍效率!
安裝那些事兒
裝這個(gè)庫(kù)特別簡(jiǎn)單,pip一把梭就完事兒:
pip install chartify
不過(guò)要提醒一下,這貨依賴bokeh,所以得先把bokeh裝上:
pip install bokeh
要是遇到版本沖突,建議創(chuàng)建個(gè)新的虛擬環(huán)境:
python -m venv chartify_env
source chartify_env/bin/activate # Linux/Mac
chartify_env\Scripts\activate # Windows
從零開(kāi)始畫圖
基礎(chǔ)柱狀圖
先從最簡(jiǎn)單的柱狀圖開(kāi)始:
import chartify import pandas as pd # 隨便整點(diǎn)數(shù)據(jù) data = pd.DataFrame({ '月份': ['1月', '2月', '3月', '4月'], '銷量': [100, 150, 200, 180] }) # 畫個(gè)最基礎(chǔ)的柱狀圖 ch = chartify.Chart(blank_labels=True) ch.plot.bar( data_frame=data, x_column='月份', y_column='銷量' ) ch.show()
溫馨提示:第一次用的時(shí)候可能會(huì)遇到字體報(bào)錯(cuò),別慌,加上這行代碼就搞定:
ch.set_font_family('Arial')
進(jìn)階折線圖
來(lái)點(diǎn)復(fù)雜的,畫個(gè)帶趨勢(shì)線的銷售數(shù)據(jù)分析圖:
import pandas as pd import numpy as np import chartify # 生成示例數(shù)據(jù) dates = pd.date_range('2023-01-01', '2023-12-31', freq='D') base_sales = np.linspace(100, 200, len(dates)) # 基礎(chǔ)趨勢(shì) noise = np.random.normal(0, 10, len(dates)) # 隨機(jī)波動(dòng) sales = base_sales + noise data = pd.DataFrame({ '日期': dates, '銷量': sales, '趨勢(shì)': base_sales }) # 畫圖 ch = chartify.Chart(blank_labels=True) ch.plot.line( data_frame=data, x_column='日期', y_column='銷量', color='#1f77b4' ) ch.plot.line( data_frame=data, x_column='日期', y_column='趨勢(shì)', color='#ff7f0e', line_style='dashed' ) ch.set_title('2023年銷量趨勢(shì)分析') ch.show()
散點(diǎn)圖與氣泡圖
數(shù)據(jù)分析離不開(kāi)散點(diǎn)圖,來(lái)看看Chartify怎么畫:
import chartify import numpy as np # 造點(diǎn)復(fù)雜數(shù)據(jù) n_points = 200 x = np.random.normal(0, 1, n_points) y = x * 0.5 + np.random.normal(0, 0.5, n_points) size = np.abs(x * y) * 50 # 氣泡大小 data = pd.DataFrame({ 'x值': x, 'y值': y, '大小': size }) ch = chartify.Chart(blank_labels=True) ch.plot.scatter( data_frame=data, x_column='x值', y_column='y值', size_column='大小', color_column='大小' # 顏色也隨值變化 ) ch.set_title('相關(guān)性分析') ch.show()
專業(yè)數(shù)據(jù)分析必備技能
多維度分析
實(shí)際工作中經(jīng)常需要分析多個(gè)維度的數(shù)據(jù),Chartify也能輕松搞定:
# 多維度銷售數(shù)據(jù) sales_data = pd.DataFrame({ '月份': np.repeat(['1月', '2月', '3月', '4月'], 3), '產(chǎn)品': np.tile(['A產(chǎn)品', 'B產(chǎn)品', 'C產(chǎn)品'], 4), '銷量': np.random.randint(100, 200, 12) }) # 分組柱狀圖 ch = chartify.Chart(blank_labels=True) ch.plot.bar( data_frame=sales_data, x_column='月份', y_column='銷量', color_column='產(chǎn)品', categorical_columns=['月份', '產(chǎn)品'] ) ch.set_title('各產(chǎn)品月度銷量對(duì)比') ch.show()
時(shí)間序列分析
金融數(shù)據(jù)分析最常用的就是時(shí)間序列了:
# 生成股票數(shù)據(jù) dates = pd.date_range('2023-01-01', '2023-12-31', freq='D') price = 100 + np.random.randn(len(dates)).cumsum() volume = np.random.randint(1000, 5000, len(dates)) stock_data = pd.DataFrame({ '日期': dates, '價(jià)格': price, '成交量': volume }) # 雙軸圖表 ch = chartify.Chart(blank_labels=True) ch.plot.line( data_frame=stock_data, x_column='日期', y_column='價(jià)格' ) ch.plot.bar( data_frame=stock_data, x_column='日期', y_column='成交量', second_axis=True # 使用第二個(gè)Y軸 ) ch.set_title('股票價(jià)格與成交量分析') ch.show()
高級(jí)可視化技巧
自定義主題
Chartify提供了強(qiáng)大的主題定制功能:
# 自定義主題 custom_theme = { 'axes.label_color': '#2c3e50', 'axes.line_color': '#34495e', 'plot.background_fill_color': '#ecf0f1', 'plot.border_fill_color': '#ffffff', 'title.text_color': '#2c3e50', 'toolbar.active_color': '#95a5a6' } ch = chartify.Chart(blank_labels=True) ch.set_theme('custom', custom_theme) ch.plot.line( data_frame=data, x_column='日期', y_column='銷量' ) ch.show()
交互式特性
Chartify基于bokeh,所以天生支持交互式特性:
ch = chartify.Chart( blank_labels=True, layout='slide_100%' ) ch.plot.scatter( data_frame=data, x_column='x值', y_column='y值', size_column='大小', tooltip_columns=['x值', 'y值', '大小'] # 添加懸停提示 ) ch.set_zoom_enabled() # 啟用縮放 ch.enable_data_labels() # 啟用數(shù)據(jù)標(biāo)簽 ch.show()
批量圖表生成
在實(shí)際工作中,經(jīng)常需要生成大量報(bào)表,Chartify也能輕松應(yīng)對(duì):
def generate_department_report(dept_data, dept_name): ch = chartify.Chart() # 銷量趨勢(shì) ch.plot.line( data_frame=dept_data, x_column='日期', y_column='銷量' ) # 添加目標(biāo)線 ch.plot.line( data_frame=dept_data, x_column='日期', y_column='目標(biāo)', line_style='dashed', color='red' ) ch.set_title(f'{dept_name}部門銷售報(bào)告') return ch # 批量生成部門報(bào)表 departments = ['銷售部', '市場(chǎng)部', '運(yùn)營(yíng)部'] charts = [] for dept in departments: # 生成部門數(shù)據(jù) dept_data = pd.DataFrame({ '日期': pd.date_range('2023-01-01', '2023-12-31', freq='D'), '銷量': np.random.normal(100, 10, 365), '目標(biāo)': np.random.normal(120, 5, 365) }) charts.append(generate_department_report(dept_data, dept)) # 保存為HTML文件 chartify.save_charts_html(charts, 'department_reports.html')
性能優(yōu)化技巧
大數(shù)據(jù)集處理
處理大數(shù)據(jù)集時(shí),可以使用數(shù)據(jù)采樣來(lái)提升性能:
def sample_data(data, n=1000): """大數(shù)據(jù)集采樣""" if len(data) > n: return data.sample(n=n, random_state=42) return data # 處理大數(shù)據(jù)集 big_data = pd.DataFrame({ 'x': np.random.normal(0, 1, 100000), 'y': np.random.normal(0, 1, 100000) }) # 采樣后繪圖 sampled_data = sample_data(big_data) ch = chartify.Chart() ch.plot.scatter( data_frame=sampled_data, x_column='x', y_column='y' ) ch.show()
內(nèi)存優(yōu)化
對(duì)于超大數(shù)據(jù)集,可以使用分塊處理:
def plot_large_dataset(file_path, chunk_size=10000): """分塊處理大數(shù)據(jù)集""" ch = chartify.Chart() for chunk in pd.read_csv(file_path, chunksize=chunk_size): sampled_chunk = sample_data(chunk, n=100) ch.plot.scatter( data_frame=sampled_chunk, x_column='x', y_column='y', alpha=0.5 ) return ch
實(shí)戰(zhàn)案例-銷售數(shù)據(jù)分析系統(tǒng)
來(lái)個(gè)完整的案例,整合前面說(shuō)的所有特性:
import chartify import pandas as pd import numpy as np from datetime import datetime, timedelta class SalesAnalysisSystem: def __init__(self): self.data = self._generate_sample_data() def _generate_sample_data(self): """生成示例數(shù)據(jù)""" dates = pd.date_range('2023-01-01', '2023-12-31', freq='D') products = ['產(chǎn)品A', '產(chǎn)品B', '產(chǎn)品C'] regions = ['華東', '華北', '華南'] # 構(gòu)建數(shù)據(jù)框 records = [] for date in dates: for product in products: for region in regions: base_sales = 100 + np.random.normal(0, 10) seasonal_factor = 1 + 0.3 * np.sin(date.month * np.pi / 6) sales = base_sales * seasonal_factor records.append({ '日期': date, '產(chǎn)品': product, '地區(qū)': region, '銷量': sales, '單價(jià)': np.random.uniform(50, 200) }) return pd.DataFrame(records) def plot_overall_trend(self): """整體銷售趨勢(shì)""" daily_sales = self.data.groupby('日期')['銷量'].sum().reset_index() ch = chartify.Chart(blank_labels=True) ch.plot.line( data_frame=daily_sales, x_column='日期', y_column='銷量' ) ch.set_title('整體銷售趨勢(shì)') return ch def plot_product_comparison(self): """產(chǎn)品銷售對(duì)比""" product_sales = self.data.groupby(['日期', '產(chǎn)品'])['銷量'].sum().reset_index() ch = chartify.Chart(blank_labels=True) ch.plot.line( data_frame=product_sales, x_column='日期', y_column='銷量', color_column='產(chǎn)品' ) ch.set_title('產(chǎn)品銷售對(duì)比') return ch def plot_regional_analysis(self): """地區(qū)銷售分析""" regional_sales = self.data.groupby('地區(qū)')['銷量'].sum().reset_index() ch = chartify.Chart(blank_labels=True) ch.plot.bar( data_frame=regional_sales, x_column='地區(qū)', y_column='銷量' ) ch.set_title('地區(qū)銷售分析') return ch def plot_price_sales_correlation(self): """價(jià)格與銷量相關(guān)性分析""" ch = chartify.Chart(blank_labels=True) ch.plot.scatter( data_frame=self.data, x_column='單價(jià)', y_column='銷量', color_column='產(chǎn)品', size_column='銷量' ) ch.set_title('價(jià)格與銷量相關(guān)性') return ch def generate_full_report(self): """生成完整報(bào)表""" charts = [ self.plot_overall_trend(), self.plot_product_comparison(), self.plot_regional_analysis(), self.plot_price_sales_correlation() ] chartify.save_charts_html(charts, 'sales_analysis_report.html') # 使用示例 system = SalesAnalysisSystem() system.generate_full_report()
這個(gè)完整的銷售數(shù)據(jù)分析系統(tǒng)展示了Chartify在實(shí)際項(xiàng)目中的應(yīng)用。
它能自動(dòng)生成各種分析圖表,還能導(dǎo)出成交互式的HTML報(bào)表,簡(jiǎn)直不要太方便!
代碼寫到這兒,你應(yīng)該能感受到Chartify的強(qiáng)大了。
它不僅讓數(shù)據(jù)可視化變得超簡(jiǎn)單,還能做出特別專業(yè)的效果。
我現(xiàn)在畫圖的速度比以前快了13倍不止,主要是不用再去查那些煩人的參數(shù)了,代碼寫起來(lái)也特別順手。
這個(gè)庫(kù)最大的優(yōu)勢(shì)就是讓你專注于數(shù)據(jù)本身,而不是糾結(jié)于圖表的細(xì)節(jié)配置。
它的API設(shè)計(jì)得非常直觀,就算是Python數(shù)據(jù)分析的新手,也能很快上手。
對(duì)于那些需要經(jīng)常做數(shù)據(jù)分析報(bào)告的同學(xué)來(lái)說(shuō),這絕對(duì)是提升效率的利器!
以上就是Python使用Chartify庫(kù)進(jìn)行數(shù)據(jù)分析繪制詳解的詳細(xì)內(nèi)容,更多關(guān)于Python Chartify庫(kù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python與數(shù)據(jù)庫(kù)交互:入門指南
這篇文章主要介紹了Python與數(shù)據(jù)庫(kù)交互:入門指南的相關(guān)資料,需要的朋友可以參考下2023-11-11Python使用pymupdf實(shí)現(xiàn)PDF加密
這篇文章主要介紹了如何使用 Python 和 wxPython 庫(kù)創(chuàng)建一個(gè)簡(jiǎn)單的圖形用戶界面(GUI)應(yīng)用程序,用于對(duì) PDF 文件進(jìn)行加密,感興趣的小伙伴可以了解下2023-08-08PyCharm安裝配置Qt Designer+PyUIC圖文教程
這篇文章主要介紹了PyCharm安裝配置Qt Designer+PyUIC圖文教程,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-05-05Python?Pygame實(shí)現(xiàn)可控制的煙花游戲
大家好,本篇文章主要講的是Python?Pygame實(shí)現(xiàn)可控制的煙花游戲,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下2022-01-01Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)篩選及提取序列中元素的方法
這篇文章主要介紹了Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)篩選及提取序列中元素的方法,涉及Python列表推導(dǎo)式、生成器表達(dá)式及filter()函數(shù)相關(guān)使用技巧,需要的朋友可以參考下2018-03-03對(duì)python 多線程中的守護(hù)線程與join的用法詳解
今天小編就為大家分享一篇對(duì)python 多線程中的守護(hù)線程與join的用法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-02-02基于Python對(duì)xsl&xslx文件進(jìn)行操作
這篇文章主要為大家詳細(xì)介紹了如何使用Python對(duì)xsl&xslx文件進(jìn)行一些基本操作,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-12-12