您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Pyecharts柱状图怎么实现
## 一、Pyecharts简介
Pyecharts是一个基于Echarts的Python可视化库,它能够生成各种交互式的图表。与Matplotlib和Seaborn等传统可视化库相比,Pyecharts具有以下优势:
1. **交互性强**:支持鼠标悬停显示数据、缩放、拖动等交互操作
2. **图表类型丰富**:提供30+种常见图表类型
3. **配置灵活**:支持高度定制化的图表配置
4. **输出多样**:可生成HTML文件、Jupyter Notebook内嵌或图片格式
## 二、环境准备
在开始使用Pyecharts之前,需要确保已安装以下环境:
```python
# 安装Pyecharts(推荐1.x以上版本)
pip install pyecharts
# 如果需要输出为图片,还需安装以下依赖
pip install pyecharts-snapshot
pip install phantomjs
from pyecharts.charts import Bar
from pyecharts import options as opts
# 准备数据
x_data = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
y_data = [5, 20, 36, 10, 75, 90]
# 创建柱状图对象
bar = Bar()
# 添加x轴数据
bar.add_xaxis(x_data)
# 添加y轴数据和系列名称
bar.add_yaxis("商品销量", y_data)
# 设置全局配置
bar.set_global_opts(
title_opts=opts.TitleOpts(title="基础柱状图"),
yaxis_opts=opts.AxisOpts(name="销量"),
xaxis_opts=opts.AxisOpts(name="商品")
)
# 渲染图表(生成HTML文件)
bar.render("basic_bar.html")
Bar()
: 创建柱状图实例add_xaxis()
: 添加x轴数据add_yaxis()
: 添加y轴数据和系列名称set_global_opts()
: 设置全局配置项render()
: 渲染生成HTML文件bar = Bar()
bar.add_xaxis(x_data)
bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
bar.add_yaxis("商家B", [15, 25, 16, 55, 48, 8])
bar.add_yaxis("商家C", [25, 10, 26, 35, 28, 50])
bar.set_global_opts(
title_opts=opts.TitleOpts(title="多系列柱状图"),
tooltip_opts=opts.TooltipOpts(trigger="axis"),
legend_opts=opts.LegendOpts(pos_left="right")
)
bar.render("multi_series_bar.html")
bar = Bar()
bar.add_xaxis(x_data)
bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90], stack="stack1")
bar.add_yaxis("商家B", [15, 25, 16, 55, 48, 8], stack="stack1")
bar.add_yaxis("商家C", [25, 10, 26, 35, 28, 50], stack="stack2")
bar.set_global_opts(
title_opts=opts.TitleOpts(title="堆叠柱状图"),
tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="shadow")
)
bar.render("stacked_bar.html")
bar = Bar()
bar.add_yaxis("商品", x_data)
bar.add_xaxis("商家A", [5, 20, 36, 10, 75, 90])
bar.add_xaxis("商家B", [15, 25, 16, 55, 48, 8])
bar.reversal_axis() # 翻转坐标轴
bar.set_global_opts(
title_opts=opts.TitleOpts(title="横向柱状图"),
tooltip_opts=opts.TooltipOpts(trigger="axis")
)
bar.render("horizontal_bar.html")
bar = Bar()
bar.add_xaxis(x_data)
bar.add_yaxis(
"商家A",
[5, 20, 36, 10, 75, 90],
itemstyle_opts=opts.ItemStyleOpts(color="#5793f3"),
label_opts=opts.LabelOpts(
position="top",
formatter="{b}: {c}",
color="#333",
font_size=12
)
)
bar.set_global_opts(
title_opts=opts.TitleOpts(title="带数据标签的柱状图"),
visualmap_opts=opts.VisualMapOpts(
min_=0,
max_=100,
orient="horizontal",
pos_left="center"
)
)
bar.render("styled_bar.html")
from pyecharts.faker import Faker
from pyecharts.globals import CurrentConfig
CurrentConfig.ONLINE_HOST = "https://cdn.jsdelivr.net/npm/echarts@4.8.0/dist/"
bar = Bar()
bar.add_xaxis(Faker.choose())
bar.add_yaxis("商家A", Faker.values())
bar.add_yaxis("商家B", Faker.values())
bar.set_global_opts(
title_opts=opts.TitleOpts(title="动态排序柱状图"),
visualmap_opts=opts.VisualMapOpts(
type_="color",
min_=0,
max_=200
),
datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")],
toolbox_opts=opts.ToolboxOpts()
)
bar.render("dynamic_sort_bar.html")
from pyecharts.charts import Bar, Timeline
from pyecharts.globals import ThemeType
tl = Timeline(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
for year in ["2018", "2019", "2020"]:
bar = Bar()
bar.add_xaxis(x_data)
bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
bar.add_yaxis("商家B", [15, 25, 16, 55, 48, 8])
bar.set_global_opts(
title_opts=opts.TitleOpts(title=f"{year}年销售情况"),
legend_opts=opts.LegendOpts(pos_right="10%")
)
tl.add(bar, year)
tl.render("timeline_bar.html")
import pandas as pd
# 模拟销售数据
data = {
"月份": ["1月", "2月", "3月", "4月", "5月", "6月"],
"产品A": [120, 132, 101, 134, 90, 230],
"产品B": [220, 182, 191, 234, 290, 330],
"产品C": [150, 232, 201, 154, 190, 330]
}
df = pd.DataFrame(data)
bar = Bar(init_opts=opts.InitOpts(width="1000px", height="600px"))
bar.add_xaxis(df["月份"].tolist())
for col in df.columns[1:]:
bar.add_yaxis(col, df[col].tolist())
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="5%"),
toolbox_opts=opts.ToolboxOpts(
feature={
"dataView": {"show": True, "readOnly": False},
"magicType": {"show": True, "type": ["line", "bar"]},
"restore": {"show": True},
"saveAsImage": {"show": True}
}
),
datazoom_opts=[opts.DataZoomOpts()]
)
bar.render("sales_analysis.html")
from pyecharts.charts import Bar, Grid
from pyecharts.commons.utils import JsCode
regions = ["华东", "华北", "华南", "华中", "西南", "西北", "东北"]
data1 = [120, 200, 150, 80, 70, 110, 130]
data2 = [90, 150, 200, 70, 60, 90, 100]
bar1 = Bar()
bar1.add_xaxis(regions)
bar1.add_yaxis("2020年", data1, category_gap="60%")
bar1.add_yaxis("2021年", data2, category_gap="60%")
bar1.set_global_opts(
title_opts=opts.TitleOpts(title="各地区销售对比", pos_left="center"),
legend_opts=opts.LegendOpts(pos_top="5%"),
tooltip_opts=opts.TooltipOpts(
trigger="axis",
formatter=JsCode(
"""function(params){
return params[0].name + '<br/>' +
params[0].seriesName + ': ' + params[0].value + '<br/>' +
params[1].seriesName + ': ' + params[1].value;
}"""
)
)
)
# 添加增长率折线图
from pyecharts.charts import Line
line = Line()
growth_rate = [(y2-y1)/y1*100 for y1, y2 in zip(data1, data2)]
line.add_xaxis(regions)
line.add_yaxis(
"增长率(%)",
growth_rate,
label_opts=opts.LabelOpts(
formatter=JsCode("function(params){return params.value.toFixed(1) + '%';}")
),
linestyle_opts=opts.LineStyleOpts(width=4),
symbol="diamond",
symbol_size=12
)
# 组合图表
grid = Grid()
grid.add(bar1, grid_opts=opts.GridOpts(pos_bottom="25%"))
grid.add(line, grid_opts=opts.GridOpts(pos_top="60%"))
grid.render("region_comparison.html")
# 在代码开头添加以下配置
from pyecharts.globals import CurrentConfig
CurrentConfig.ONLINE_HOST = "https://cdn.jsdelivr.net/npm/echarts@4.8.0/dist/"
# 或者手动指定字体
bar.set_global_opts(
title_opts=opts.TitleOpts(title="中文标题"),
legend_opts=opts.LegendOpts(textstyle_opts=opts.TextStyleOpts(font_family="Microsoft YaHei"))
)
# 初始化时设置
bar = Bar(init_opts=opts.InitOpts(width="800px", height="500px"))
# 或者通过render方法设置
bar.render("output.html", width="100%", height="600px")
# 需要安装pyecharts-snapshot和phantomjs
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot
make_snapshot(snapshot, bar.render(), "bar.png")
Pyecharts提供了强大而灵活的柱状图实现方式,从基础的单系列柱状图到复杂的多系列、堆叠、动态排序等高级图表都能轻松实现。通过本文的介绍,你应该已经掌握了:
Pyecharts的官方文档提供了更全面的API参考和示例代码,建议在实际开发中结合官方文档使用。随着对Pyecharts的深入掌握,你可以创建出更加专业、美观的数据可视化作品。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。