# Python中pyecharts如何繪制柱狀圖
## 一、pyecharts簡介
### 1.1 什么是pyecharts
pyecharts是一個基于ECharts的Python可視化庫,由百度團隊開源維護。它允許開發者使用Python代碼生成ECharts風格的交互式圖表,支持折線圖、柱狀圖、餅圖、散點圖等多種圖表類型。
主要特點:
- 完全兼容Python 2/3環境
- 支持Jupyter Notebook環境直接渲染
- 可生成獨立的HTML文件
- 提供簡潔的API設計
- 支持鏈式調用語法
### 1.2 安裝與配置
安裝pyecharts非常簡單,使用pip即可完成:
```bash
pip install pyecharts
如果需要使用最新版本,可以從GitHub安裝:
pip install git+https://github.com/pyecharts/pyecharts.git
推薦同時安裝以下附加組件:
pip install pyecharts-jupyter-installer # Jupyter支持
pip install pyecharts-snapshot # 圖片導出
下面是一個最基本的柱狀圖示例:
from pyecharts.charts import Bar
# 創建柱狀圖對象
bar = Bar()
# 添加x軸數據
bar.add_xaxis(["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"])
# 添加y軸數據
bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
# 渲染生成HTML文件
bar.render("simple_bar.html")
這段代碼會生成一個包含6個柱子的柱狀圖,顯示不同商品的銷售數量。
要比較多個系列的數據,可以添加多個y軸系列:
bar = Bar()
bar.add_xaxis(["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"])
bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
bar.add_yaxis("商家B", [15, 6, 45, 20, 35, 66])
bar.render("multi_series_bar.html")
通過設置reversal_axis
參數可以創建橫向柱狀圖:
bar = Bar()
bar.add_xaxis(["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"])
bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
bar.reversal_axis()
bar.render("horizontal_bar.html")
pyecharts提供了豐富的樣式定制選項:
bar = Bar()
bar.add_xaxis(["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"])
bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90],
itemstyle_opts={
"color": "#3398DB", # 設置柱子顏色
"borderRadius": [5, 5, 0, 0] # 圓角設置
})
bar.set_global_opts(
title_opts={"text": "銷售數據統計", "subtext": "2023年第一季度"},
visualmap_opts={
"type": "color",
"min": 0,
"max": 100,
"in_range": {"color": ["#50a3ba", "#eac736", "#d94e5d"]}
}
)
bar.render("styled_bar.html")
可以自定義數據標簽和提示框的顯示:
bar = Bar()
bar.add_xaxis(["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"])
bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90],
label_opts={"position": "top", "color": "black"}, # 標簽在柱子上方
tooltip_opts={"formatter": ": {c}件"}) # 自定義提示框內容
bar.render("labeled_bar.html")
可以自定義坐標軸的樣式和范圍:
bar = Bar()
bar.add_xaxis(["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"])
bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
bar.set_global_opts(
xaxis_opts={
"name": "商品類別",
"name_location": "middle",
"name_gap": 30,
"axisLabel": {"interval": 0, "rotate": 45}
},
yaxis_opts={
"name": "銷售數量",
"min": 0,
"max": 100,
"splitNumber": 5
}
)
bar.render("axis_bar.html")
通過設置stack
參數可以創建堆疊柱狀圖:
bar = Bar()
bar.add_xaxis(["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"])
bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90], stack="stack1")
bar.add_yaxis("商家B", [15, 6, 45, 20, 35, 66], stack="stack1")
bar.set_series_opts(label_opts={"position": "inside"})
bar.set_global_opts(title_opts={"text": "堆疊柱狀圖示例"})
bar.render("stacked_bar.html")
使用Bar
的mark_line
和mark_point
可以模擬瀑布圖效果:
bar = Bar()
bar.add_xaxis(["初始", "產品A", "產品B", "產品C", "產品D", "總計"])
bar.add_yaxis("", [1000, 200, 300, -100, 400, 0],
itemstyle_opts={
"color": function(params):
if params.dataIndex == 0 or params.dataIndex == 5:
return "#5793f3"
elif params.data > 0:
return "#d14a61"
else:
return "#675bba"
})
bar.set_global_opts(
title_opts={"text": "銷售利潤瀑布圖"},
tooltip_opts={"trigger": "axis", "axisPointer": {"type": "shadow"}}
)
bar.render("waterfall_bar.html")
使用Polar
組件可以創建極坐標柱狀圖:
from pyecharts.charts import Polar
polar = Polar()
polar.add_schema(radiusaxis_opts={"type": "category", "data": ["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"]})
polar.add("商家A", [5, 20, 36, 10, 75, 90], type_="bar")
polar.render("polar_bar.html")
對于數據量大的情況,可以添加縮放功能:
bar = Bar()
bar.add_xaxis([f"商品{i}" for i in range(1, 101)])
bar.add_yaxis("銷量", [i*2 for i in range(1, 101)])
bar.set_global_opts(
datazoom_opts=[{"type": "inside"}, {"type": "slider"}],
title_opts={"text": "大數據量柱狀圖"}
)
bar.render("datazoom_bar.html")
pyecharts支持動態數據更新,適合實時數據展示:
from pyecharts import options as opts
from pyecharts.charts import Bar, Timeline
timeline = Timeline()
for year in range(2018, 2023):
bar = Bar()
bar.add_xaxis(["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"])
bar.add_yaxis("銷量", [i*(year-2017) for i in [5, 20, 36, 10, 75, 90]])
bar.set_global_opts(title_opts=opts.TitleOpts(title=f"{year}年銷售數據"))
timeline.add(bar, str(year))
timeline.render("timeline_bar.html")
可以添加JavaScript回調函數處理點擊事件:
bar = Bar()
bar.add_xaxis(["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"])
bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
bar.set_global_opts(
title_opts={"text": "帶點擊事件的柱狀圖"}
)
bar.add_js_funcs("""
function(params) {
if(params.componentType === 'series') {
alert('你點擊了' + params.name + ',值為' + params.value);
}
}
""")
bar.render("clickable_bar.html")
假設我們有一份銷售數據CSV文件:
import pandas as pd
from pyecharts.charts import Bar
# 讀取數據
df = pd.read_csv("sales_data.csv")
# 按產品類別匯總
category_sales = df.groupby("category")["sales"].sum().sort_values()
# 創建柱狀圖
bar = Bar()
bar.add_xaxis(category_sales.index.tolist())
bar.add_yaxis("銷售額", category_sales.values.tolist())
bar.set_global_opts(
title_opts={"text": "各產品類別銷售額對比"},
yaxis_opts={"name": "銷售額(萬元)"}
)
bar.render("sales_analysis.html")
分析用戶在不同時段的活躍度:
import random
from pyecharts.charts import Bar
from pyecharts import options as opts
hours = [f"{i}:00" for i in range(24)]
active_users = [random.randint(100, 1000) for _ in range(24)]
bar = Bar()
bar.add_xaxis(hours)
bar.add_yaxis("活躍用戶數", active_users)
bar.set_global_opts(
title_opts=opts.TitleOpts(title="24小時用戶活躍度"),
xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=45)),
datazoom_opts=[opts.DataZoomOpts()]
)
bar.render("user_activity.html")
比較不同地區、不同產品的銷售情況:
from pyecharts.charts import Bar
from pyecharts import options as opts
regions = ["華東", "華北", "華南", "華中", "西北"]
products = ["手機", "電腦", "平板", "配件"]
data = [
[1200, 800, 600, 400],
[900, 700, 500, 300],
[1100, 750, 550, 350],
[1000, 850, 450, 250],
[800, 600, 400, 200]
]
bar = Bar()
bar.add_xaxis(products)
for i, region in enumerate(regions):
bar.add_yaxis(region, data[i], stack="stack1")
bar.set_global_opts(
title_opts=opts.TitleOpts(title="各地區產品銷售情況"),
tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="shadow"),
legend_opts=opts.LegendOpts(pos_top="10%")
)
bar.render("region_product_analysis.html")
如果圖表中中文顯示為方框,需要設置中文字體:
from pyecharts.globals import ThemeType
bar = Bar(init_opts={"theme": ThemeType.LIGHT})
bar.add_xaxis(["襯衫", "羊毛衫", "雪紡衫"])
bar.add_yaxis("銷量", [5, 20, 36])
bar.set_global_opts(
title_opts={"text": "中文標題"},
legend_opts={"textstyle_opts": {"fontFamily": "Microsoft YaHei"}}
)
bar.set_series_opts(label_opts={"fontFamily": "Microsoft YaHei"})
bar.render("chinese_bar.html")
當數據量很大時,可以采取以下優化措施:
1. 使用large_threshold
參數
2. 啟用數據采樣
3. 使用WebGL渲染
bar = Bar()
bar.add_xaxis([f"數據{i}" for i in range(1000)])
bar.add_yaxis("", [i % 100 for i in range(1000)],
large_threshold=2000)
bar.set_global_opts(datazoom_opts=[{"type": "inside"}])
bar.render("large_data_bar.html")
要導出高質量圖片,建議使用pyecharts-snapshot
:
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot
bar = Bar()
bar.add_xaxis(["襯衫", "羊毛衫", "雪紡衫"])
bar.add_yaxis("銷量", [5, 20, 36])
make_snapshot(snapshot, bar.render(), "bar.png")
pyecharts提供了強大而靈活的柱狀圖繪制功能,從簡單的靜態圖表到復雜的交互式可視化都能輕松實現。通過本文的介紹,你應該已經掌握了:
pyecharts的官方文檔非常完善,建議遇到問題時優先查閱官方文檔。隨著版本的更新,pyecharts會不斷增加新功能,建議保持關注其GitHub倉庫獲取最新動態。
”`
注:本文代碼示例基于pyecharts 1.x版本,部分API在2.0版本中可能有變化。實際使用時請參考對應版本的官方文檔。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。