Python使用Chartify庫進行數(shù)據(jù)分析繪制詳解
前言
數(shù)據(jù)可視化這事兒,搞過的都知道有多費勁。
用matplotlib畫個圖要調(diào)半天參數(shù),才能讓圖表看起來稍微順眼一點;seaborn雖然畫出來的圖確實好看,但是配置項太多,記不住,每次用都要查文檔。
直到遇見了Chartify這個寶貝疙瘩,簡直就是救命稻草啊!這玩意兒是Spotify開源的,我愿稱之為“懶人神器”。
它提供了簡潔易用的API,讓我們能夠快速地繪制出美觀且專業(yè)的圖表,無需像使用matplotlib和seaborn那樣花費大量時間去調(diào)整各種復(fù)雜的參數(shù),大大提高了數(shù)據(jù)可視化的效率,讓數(shù)據(jù)可視化變得輕松又愉快。
為啥要用Chartify
說實話,我一開始也不信這個庫能有多厲害。
畢竟市面上的可視化庫多如牛毛,matplotlib、seaborn、plotly哪個不是響當當?shù)拿郑?/p>
但是實際用下來才發(fā)現(xiàn),這些傳統(tǒng)庫都有一個共同的痛點:配置太復(fù)雜。
拿matplotlib來說,畫個簡單的折線圖都得寫好幾行代碼:
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()看到差別了吧?這就是為啥我說它能提升13倍效率!
安裝那些事兒
裝這個庫特別簡單,pip一把梭就完事兒:
pip install chartify
不過要提醒一下,這貨依賴bokeh,所以得先把bokeh裝上:
pip install bokeh
要是遇到版本沖突,建議創(chuàng)建個新的虛擬環(huán)境:
python -m venv chartify_env
source chartify_env/bin/activate # Linux/Mac
chartify_env\Scripts\activate # Windows
從零開始畫圖
基礎(chǔ)柱狀圖
先從最簡單的柱狀圖開始:
import chartify
import pandas as pd
# 隨便整點數(shù)據(jù)
data = pd.DataFrame({
'月份': ['1月', '2月', '3月', '4月'],
'銷量': [100, 150, 200, 180]
})
# 畫個最基礎(chǔ)的柱狀圖
ch = chartify.Chart(blank_labels=True)
ch.plot.bar(
data_frame=data,
x_column='月份',
y_column='銷量'
)
ch.show()溫馨提示:第一次用的時候可能會遇到字體報錯,別慌,加上這行代碼就搞定:
ch.set_font_family('Arial')進階折線圖
來點復(fù)雜的,畫個帶趨勢線的銷售數(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ǔ)趨勢
noise = np.random.normal(0, 10, len(dates)) # 隨機波動
sales = base_sales + noise
data = pd.DataFrame({
'日期': dates,
'銷量': sales,
'趨勢': 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='趨勢',
color='#ff7f0e',
line_style='dashed'
)
ch.set_title('2023年銷量趨勢分析')
ch.show()散點圖與氣泡圖
數(shù)據(jù)分析離不開散點圖,來看看Chartify怎么畫:
import chartify
import numpy as np
# 造點復(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ù)分析必備技能
多維度分析
實際工作中經(jīng)常需要分析多個維度的數(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)品月度銷量對比')
ch.show()時間序列分析
金融數(shù)據(jù)分析最常用的就是時間序列了:
# 生成股票數(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,
'價格': price,
'成交量': volume
})
# 雙軸圖表
ch = chartify.Chart(blank_labels=True)
ch.plot.line(
data_frame=stock_data,
x_column='日期',
y_column='價格'
)
ch.plot.bar(
data_frame=stock_data,
x_column='日期',
y_column='成交量',
second_axis=True # 使用第二個Y軸
)
ch.set_title('股票價格與成交量分析')
ch.show()高級可視化技巧
自定義主題
Chartify提供了強大的主題定制功能:
# 自定義主題
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ù)標簽
ch.show()批量圖表生成
在實際工作中,經(jīng)常需要生成大量報表,Chartify也能輕松應(yīng)對:
def generate_department_report(dept_data, dept_name):
ch = chartify.Chart()
# 銷量趨勢
ch.plot.line(
data_frame=dept_data,
x_column='日期',
y_column='銷量'
)
# 添加目標線
ch.plot.line(
data_frame=dept_data,
x_column='日期',
y_column='目標',
line_style='dashed',
color='red'
)
ch.set_title(f'{dept_name}部門銷售報告')
return ch
# 批量生成部門報表
departments = ['銷售部', '市場部', '運營部']
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),
'目標': 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ù)據(jù)采樣來提升性能:
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)化
對于超大數(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實戰(zhàn)案例-銷售數(shù)據(jù)分析系統(tǒng)
來個完整的案例,整合前面說的所有特性:
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,
'單價': np.random.uniform(50, 200)
})
return pd.DataFrame(records)
def plot_overall_trend(self):
"""整體銷售趨勢"""
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('整體銷售趨勢')
return ch
def plot_product_comparison(self):
"""產(chǎn)品銷售對比"""
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)品銷售對比')
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):
"""價格與銷量相關(guān)性分析"""
ch = chartify.Chart(blank_labels=True)
ch.plot.scatter(
data_frame=self.data,
x_column='單價',
y_column='銷量',
color_column='產(chǎn)品',
size_column='銷量'
)
ch.set_title('價格與銷量相關(guān)性')
return ch
def generate_full_report(self):
"""生成完整報表"""
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()這個完整的銷售數(shù)據(jù)分析系統(tǒng)展示了Chartify在實際項目中的應(yīng)用。
它能自動生成各種分析圖表,還能導出成交互式的HTML報表,簡直不要太方便!
代碼寫到這兒,你應(yīng)該能感受到Chartify的強大了。
它不僅讓數(shù)據(jù)可視化變得超簡單,還能做出特別專業(yè)的效果。
我現(xiàn)在畫圖的速度比以前快了13倍不止,主要是不用再去查那些煩人的參數(shù)了,代碼寫起來也特別順手。
這個庫最大的優(yōu)勢就是讓你專注于數(shù)據(jù)本身,而不是糾結(jié)于圖表的細節(jié)配置。
它的API設(shè)計得非常直觀,就算是Python數(shù)據(jù)分析的新手,也能很快上手。
對于那些需要經(jīng)常做數(shù)據(jù)分析報告的同學來說,這絕對是提升效率的利器!
以上就是Python使用Chartify庫進行數(shù)據(jù)分析繪制詳解的詳細內(nèi)容,更多關(guān)于Python Chartify庫的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Pandas庫中isnull函數(shù)的實現(xiàn)
isnull()是Pandas庫中DataFrame和Series對象的一個函數(shù),用于檢測數(shù)據(jù)中的缺失值,本文主要介紹了Pandas庫中isnull函數(shù)的實現(xiàn),具有一定參考價值,感興趣的可以了解一下2024-07-07
Python3 + Appium + 安卓模擬器實現(xiàn)APP自動化測試并生成測試報告
這篇文章主要介紹了Python3 + Appium + 安卓模擬器實現(xiàn)APP自動化測試并生成測試報告,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01
解決python 3 urllib 沒有 urlencode 屬性的問題
今天小編就為大家分享一篇解決python 3 urllib 沒有 urlencode 屬性的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
Django1.9 加載通過ImageField上傳的圖片方法
今天小編就為大家分享一篇Django1.9 加載通過ImageField上傳的圖片方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05

