Python可视化神器pyecharts绘制柱状图

2022-07-13,,,,

主题介绍

pyecharts里面有很多的主题可以供我们选择,我们可以根据自己的需要完成主题的配置,这样就告别了软件的限制,可以随意的发挥自己的艺术细胞了。

图表参数

'''
def add_yaxis(
# 系列名称,用于 tooltip 的显示,legend 的图例筛选。
series_name: str,

# 系列数据
y_axis: sequence[numeric, opts.baritem, dict],
# 是否选中图例
is_selected: bool = true,
# 使用的 x 轴的 index,在单个图表实例中存在多个 x 轴的时候有用。
xaxis_index: optional[numeric] = none,
# 使用的 y 轴的 index,在单个图表实例中存在多个 y 轴的时候有用。
yaxis_index: optional[numeric] = none,

# 是否启用图例 hover 时的联动高亮
is_legend_hover_link: bool = true,
# 系列 label 颜色
color: optional[str] = none,

# 是否显示柱条的背景色。通过 backgroundstyle 配置背景样式。
is_show_background: bool = false,

# 每一个柱条的背景样式。需要将 showbackground 设置为 true 时才有效。
background_style: types.union[types.barbackground, dict, none] = none,

# 数据堆叠,同个类目轴上系列配置相同的 stack 值可以堆叠放置。
stack: optional[str] = none,

# 柱条的宽度,不设时自适应。
# 可以是绝对值例如 40 或者百分数例如 '60%'。百分数基于自动计算出的每一类目的宽度。
# 在同一坐标系上,此属性会被多个 'bar' 系列共享。此属性应设置于此坐标系中最后一个 'bar' 系列上才会生效,并且是对此坐标系中所有 'bar' 系列生效。
bar_width: types.union[types.numeric, str] = none,

# 柱条的最大宽度。比 barwidth 优先级高。
bar_max_width: types.union[types.numeric, str] = none,

# 柱条的最小宽度。在直角坐标系中,默认值是 1。否则默认值是 null。比 barwidth 优先级高。
bar_min_width: types.union[types.numeric, str] = none,

# 柱条最小高度,可用于防止某数据项的值过小而影响交互。
bar_min_height: types.numeric = 0,

# 同一系列的柱间距离,默认为类目间距的 20%,可设固定值
category_gap: union[numeric, str] = "20%",

# 不同系列的柱间距离,为百分比(如 '30%',表示柱子宽度的 30%)。
# 如果想要两个系列的柱子重叠,可以设置 gap 为 '-100%'。这在用柱子做背景的时候有用。
gap: optional[str] = "30%",

# 是否开启大数据量优化,在数据图形特别多而出现卡顿时候可以开启。
# 开启后配合 largethreshold 在数据量大于指定阈值的时候对绘制进行优化。
# 缺点:优化后不能自定义设置单个数据项的样式。
is_large: bool = false,

# 开启绘制优化的阈值。
large_threshold: types.numeric = 400,

# 使用 dimensions 定义 series.data 或者 dataset.source 的每个维度的信息。
# 注意:如果使用了 dataset,那么可以在 dataset.source 的第一行/列中给出 dimension 名称。
# 于是就不用在这里指定 dimension。
# 但是,如果在这里指定了 dimensions,那么 echarts 不再会自动从 dataset.source 的第一行/列中获取维度信息。
dimensions: types.union[types.sequence, none] = none,

# 当使用 dataset 时,serieslayoutby 指定了 dataset 中用行还是列对应到系列上,也就是说,系列“排布”到 dataset 的行还是列上。可取值:
# 'column':默认,dataset 的列对应于系列,从而 dataset 中每一列是一个维度(dimension)。
# 'row':dataset 的行对应于系列,从而 dataset 中每一行是一个维度(dimension)。
series_layout_by: str = "column",

# 如果 series.data 没有指定,并且 dataset 存在,那么就会使用 dataset。
# datasetindex 指定本系列使用那个 dataset。
dataset_index: types.numeric = 0,

# 是否裁剪超出坐标系部分的图形。柱状图:裁掉所有超出坐标系的部分,但是依然保留柱子的宽度
is_clip: bool = true,

# 柱状图所有图形的 zlevel 值。
z_level: types.numeric = 0,

# 柱状图组件的所有图形的z值。控制图形的前后顺序。
# z值小的图形会被z值大的图形覆盖。
# z相比zlevel优先级更低,而且不会创建新的 canvas。
z: types.numeric = 2,

# 标签配置项,参考 `series_options.labelopts`
label_opts: union[opts.labelopts, dict] = opts.labelopts(),

# 标记点配置项,参考 `series_options.markpointopts`
markpoint_opts: union[opts.markpointopts, dict, none] = none,

# 标记线配置项,参考 `series_options.marklineopts`
markline_opts: union[opts.marklineopts, dict, none] = none,

# 提示框组件配置项,参考 `series_options.tooltipopts`
tooltip_opts: union[opts.tooltipopts, dict, none] = none,

# 图元样式配置项,参考 `series_options.itemstyleopts`
itemstyle_opts: union[opts.itemstyleopts, dict, none] = none,

# 可以定义 data 的哪个维度被编码成什么。
encode: types.union[types.jsfunc, dict, none] = none,
)

'''

我们可以进行图表参数的配置,完成我们需要的结果展示。

主题详解

下面列举了比较详细的主题风格,随意搭配,碰撞出不一样的火花!

from pyecharts.globals import themetype
help(themetype)
"""
{"theme": themetype.macarons}

builtin_themes = ['light', 'dark', 'white']
|
| chalk = 'chalk' #粉笔风
|
| dark = 'dark' #暗黑风
|
| essos = 'essos' #厄索斯大陆
|
| infographic = 'infographic' #信息图
|
| light = 'light' #明亮风格
|
| macarons = 'macarons' #马卡龙
|
| purple_passion = 'purple-passion' #紫色激情
|
| roma = 'roma' #石榴
|
| romantic = 'romantic' #浪漫风
|
| shine = 'shine' #闪耀风
|
| vintage = 'vintage' #复古风
|
| walden = 'walden' #瓦尔登湖
|
| westeros = 'westeros' #维斯特洛大陆
|
| white = 'white' #洁白风
|
| wonderland = 'wonderland' #仙境
"""

柱状图模板系列

海量数据柱状图动画展示

非常多的数据集,我们需要展示的话,我们可以利用这个模板进行展示,下面由于数据量过多我就不展示全部的数据了。

import pyecharts.options as opts
from pyecharts.charts import bar
category = ["类目{}".format(i) for i in range(0, 100)]
red_bar = ['数据集非常多!!!!']
(
bar(init_opts=opts.initopts(width="1500px", height="700px"))
.add_xaxis(xaxis_data=category)
.add_yaxis(
series_name="系列1", y_axis=red_bar, label_opts=opts.labelopts(is_show=false)
)
.add_yaxis(
series_name="系列2",
y_axis=blue_bar,
label_opts=opts.labelopts(is_show=false),
)
.set_global_opts(
title_opts=opts.titleopts(title="柱状图动画延迟"),
xaxis_opts=opts.axisopts(splitline_opts=opts.splitlineopts(is_show=false)),
yaxis_opts=opts.axisopts(
axistick_opts=opts.axistickopts(is_show=true),
splitline_opts=opts.splitlineopts(is_show=true),
),
)
.render("柱状图动画延迟.html")
)
print("图表已生成!请查收!")

收入支出柱状图(适用于记账)

我们在日常的生活中,有收入也有支出,这个模板就是把收入和支出直观的展示在读者面前。

from pyecharts.charts import bar
from pyecharts import options as opts
# 一般不适用
x_data = [f"11月{str(i)}日" for i in range(1, 12)]
y_total = [0, 900, 1245, 1530, 1376, 1376, 1511, 1689, 1856, 1495, 1292]
y_in = [900, 345, 393, "-", "-", 135, 178, 286, "-", "-", "-"]
y_out = ["-", "-", "-", 108, 154, "-", "-", "-", 119, 361, 203]
bar = (
bar()
.add_xaxis(xaxis_data=x_data)
.add_yaxis(
series_name="",
y_axis=y_total,
stack="总量",
itemstyle_opts=opts.itemstyleopts(color="rgba(0,0,0,0)"),
)
.add_yaxis(series_name="收入", y_axis=y_in, stack="总量")
.add_yaxis(series_name="支出", y_axis=y_out, stack="总量")
.set_global_opts(yaxis_opts=opts.axisopts(type_="value"))
.render("收入支出柱状图.html")
)
print("图表已生成!请查收!")

三维数据叠加

from pyecharts import options as opts
from pyecharts.charts import bar
from pyecharts.faker import faker
c = (
bar()
.add_xaxis(faker.choose())
.add_yaxis("商家a", faker.values(), stack="stack1")
.add_yaxis("商家b", faker.values(), stack="stack1")
.add_yaxis("商家c", faker.values(),stack="stack1")
.set_series_opts(label_opts=opts.labelopts(is_show=false))
.set_global_opts(title_opts=opts.titleopts(title="标题"))
.render("三维数据折叠.html")
)
print("图表已生成!查收!")

柱状图与折线图多维展示(同屏展示)

柱状图里面也有折线图,适合我们在特定情况下进行数据展示,效果还是比较的直观,方便我们可以直接get到数据的价值。

import pyecharts.options as opts
from pyecharts.charts import bar, line
x_data = ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"]

bar = (
bar(init_opts=opts.initopts(width="1100px", height="600px"))
.add_xaxis(xaxis_data=x_data)
.add_yaxis(
series_name="蒸发量",
y_axis=[
2.0,
4.9,
7.0,
23.2,
25.6,
76.7,
135.6,
162.2,
32.6,
20.0,
6.4,
3.3,
],
label_opts=opts.labelopts(is_show=false),
)
.add_yaxis(
series_name="降水量",
y_axis=[
2.6,
5.9,
9.0,
26.4,
28.7,
70.7,
175.6,
182.2,
48.7,
18.8,
6.0,
2.3,
],
label_opts=opts.labelopts(is_show=false),
)
.extend_axis(
yaxis=opts.axisopts(
name="温度",
type_="value",
min_=0,
max_=25,
interval=5,
axislabel_opts=opts.labelopts(formatter="{value} °c"),
)
)
.set_global_opts(
tooltip_opts=opts.tooltipopts(
is_show=true, trigger="axis", axis_pointer_type="cross"
),
xaxis_opts=opts.axisopts(
name='月份',
name_location='middle',
name_gap=30, # 标签与轴线之间的距离,默认为20,最好不要设置20
name_textstyle_opts=opts.textstyleopts(
font_family='times new roman',
font_size=16, # 标签字体大小
# type_="category",
# axispointer_opts=opts.axispointeropts(is_show=true, type_="shadow"),
)),
yaxis_opts=opts.axisopts(
name="水量",
type_="value",
min_=0,
max_=250,
interval=50,
axislabel_opts=opts.labelopts(formatter="{value} ml"),
axistick_opts=opts.axistickopts(is_show=true),
splitline_opts=opts.splitlineopts(is_show=true),
),
)
)

line = (
line()
.add_xaxis(xaxis_data=x_data)
.add_yaxis(
series_name="平均温度",
yaxis_index=1,
y_axis=[2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2],
label_opts=opts.labelopts(is_show=false),
)
)

bar.overlap(line).render("折线图-柱状图多维展示.html")

print("图表已生成!请查收!")

import pyecharts.options as opts
from pyecharts.charts import bar, line
colors = ["#5793f3", "#d14a61", "#675bba"]
x_data = ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"]
legend_list = ["蒸发量", "降水量", "平均温度"]
evaporation_capacity = [
2.0,
4.9,
7.0,
23.2,
25.6,
76.7,
135.6,
162.2,
32.6,
20.0,
6.4,
3.3,
]
rainfall_capacity = [
2.6,
5.9,
9.0,
26.4,
28.7,
70.7,
175.6,
182.2,
48.7,
18.8,
6.0,
2.3,
]
average_temperature = [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2]

bar = (
bar(init_opts=opts.initopts(width="1100px", height="600px"))
.add_xaxis(xaxis_data=x_data)
.add_yaxis(
series_name="蒸发量",
y_axis=evaporation_capacity,
yaxis_index=0,
color=colors[1],
)
.add_yaxis(
series_name="降水量", y_axis=rainfall_capacity, yaxis_index=1, color=colors[0]
)
.extend_axis(
yaxis=opts.axisopts(
name="蒸发量",
type_="value",
min_=0,
max_=250,
position="right",
axisline_opts=opts.axislineopts(
linestyle_opts=opts.linestyleopts(color=colors[1])
),
axislabel_opts=opts.labelopts(formatter="{value} ml"),
)
)
.extend_axis(
yaxis=opts.axisopts(
type_="value",
name="温度",
min_=0,
max_=25,
position="left",
axisline_opts=opts.axislineopts(
linestyle_opts=opts.linestyleopts(color=colors[2])
),
axislabel_opts=opts.labelopts(formatter="{value} °c"),
splitline_opts=opts.splitlineopts(
is_show=true, linestyle_opts=opts.linestyleopts(opacity=1)
),
)
)
.set_global_opts(
yaxis_opts=opts.axisopts(
type_="value",
name="降水量",
min_=0,
max_=250,
position="right",
offset=80,
axisline_opts=opts.axislineopts(
linestyle_opts=opts.linestyleopts(color=colors[0])
),
axislabel_opts=opts.labelopts(formatter="{value} ml"),
),
tooltip_opts=opts.tooltipopts(trigger="axis", axis_pointer_type="cross"),
)
)

line = (
line()
.add_xaxis(xaxis_data=x_data)
.add_yaxis(
series_name="平均温度", y_axis=average_temperature, yaxis_index=2, color=colors[2]
)
)

bar.overlap(line).render("多维展示显示数据.html")

单列多维数据展示

from pyecharts import options as opts
from pyecharts.charts import bar
from pyecharts.commons.utils import jscode
from pyecharts.globals import themetype
'''
功能:定义多个列表,一个单列柱状图里面可以显示多个产品的数量(显示各自所占比例)达到一图多效果展示
应用场景:比如有3个产品,分别在星期一到星期天有不同的销售额,每一天三个不同的产品也都有各自的销售额
需要同时展示出这些信息,并分析出每一个产品在一天中所占比例是多少
涉及知识:列表里面嵌套多个字典
'''
list2 = [
{"value": 12, "percent": 12 / (12 + 3)}, # 对于各自的值,同时对于各自的百分比
{"value": 23, "percent": 23 / (23 + 21)},
{"value": 33, "percent": 33 / (33 + 5)},
{"value": 3, "percent": 3 / (3 + 52)},
{"value": 33, "percent": 33 / (33 + 43)},
{"value": 45, "percent": 45 / (45 + 3)},
{"value": 23, "percent": 23 / (23 + 13)},
]

list3 = [
{"value": 3, "percent": 3 / (12 + 3)},
{"value": 21, "percent": 21 / (23 + 21)},
{"value": 5, "percent": 5 / (33 + 5)},
{"value": 52, "percent": 52 / (3 + 52)},
{"value": 43, "percent": 43 / (33 + 43)},
{"value": 3, "percent": 45 / (45 + 3)},
{"value": 13, "percent": 13 / (23 + 13)},
]

# 可以添加多个列表
# list4=[]

c = (
bar(init_opts=opts.initopts(theme=themetype.light))
.add_xaxis([1, 2, 3, 4, 5, 6, 7]) # 横坐标变量参数
# 数据堆叠,同个类目轴上系列配置相同的 stack 值可以堆叠放置
# 同一系列的柱间距离,默认为类目间距的 20%,可设固定值
.add_yaxis("产品1", list2, stack="stack1", category_gap="50%")
.add_yaxis("产品2", list3, stack="stack1", category_gap="50%")
.set_series_opts(
label_opts=opts.labelopts(
position="right",
formatter=jscode(
"function(x){return number(x.data.percent * 100).tofixed() + '%';}"
),
)
)
# x y轴的系列配置
.set_global_opts(title_opts=opts.titleopts(title="标题"),
xaxis_opts=opts.axisopts(
name='星期',
name_location='middle',
name_gap=30, # 标签与轴线之间的距离,默认为20,最好不要设置20
name_textstyle_opts=opts.textstyleopts(
font_family='times new roman',
font_size=16 # 标签字体大小
)),
yaxis_opts=opts.axisopts(
name='数量',
name_location='middle',
name_gap=30,
name_textstyle_opts=opts.textstyleopts(
font_family='times new roman',
font_size=16
# font_weight='bolder',
)),
# toolbox_opts=opts.toolboxopts() # 工具选项
)
.render("单列多维占比层次柱状图.html")
)
print("图表已生成!请查收!")

3d柱状图

这类图表一般不会用到,但是pyecharts也可以生成这种炫酷的3d模板,来看看吧!

上述3d图形都可以通过鼠标进行控制,翻转

import random
from pyecharts import options as opts
from pyecharts.charts import bar3d
x_data = y_data = list(range(10))
def generate_data():
data = []
for j in range(10):
for k in range(10):
value = random.randint(0, 9)
data.append([j, k, value * 2 + 4])
return data
bar3d = bar3d(init_opts=opts.initopts(width="1500px", height="700px"))
for _ in range(10):
bar3d.add(
"",
generate_data(),
shading="lambert",
xaxis3d_opts=opts.axis3dopts(data=x_data, type_="value"),
yaxis3d_opts=opts.axis3dopts(data=y_data, type_="value"),
zaxis3d_opts=opts.axis3dopts(type_="value"),
)
bar3d.set_global_opts(title_opts=opts.titleopts("bar3d-堆叠柱状图示例"))
bar3d.set_series_opts(**{"stack": "stack"})
bar3d.render("3d堆叠柱状图.html")
import random
from pyecharts import options as opts
from pyecharts.charts import bar3d
from pyecharts.faker import faker
data = [(i, j, random.randint(0, 12)) for i in range(6) for j in range(24)]
c = (
bar3d(init_opts=opts.initopts(width="1500px", height="700px"))
.add(
"",
[[d[1], d[0], d[2]] for d in data],
xaxis3d_opts=opts.axis3dopts(faker.clock, type_="category"),
yaxis3d_opts=opts.axis3dopts(faker.week_en, type_="category"),
zaxis3d_opts=opts.axis3dopts(type_="value"),
)
.set_global_opts(
visualmap_opts=opts.visualmapopts(max_=20),
title_opts=opts.titleopts(title="bar3d-基本示例"),
)
.render("3d柱状图_1.html")
)

柱状图的模板大全差不多都是这些了,下期文章我们一起领略折线图的魅力吧!

到此这篇关于python可视化神器pyecharts绘制柱状图的文章就介绍到这了,更多相关python pyecharts内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《Python可视化神器pyecharts绘制柱状图.doc》

下载本文的Word格式文档,以方便收藏与打印。