[图表]pyecharts模块-柱状图2

先来看代码:

from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.faker import Faker


x = Faker.dogs + Faker.animal
xlen = len(x)
y = []
for idx, item in enumerate(x):
    if idx <= xlen / 2:
        y.append(
            opts.BarItem(
                name=item,
                value=(idx + 1) * 10,
                itemstyle_opts=opts.ItemStyleOpts(color="#749f83"),
            )
        )
    else:
        y.append(
            opts.BarItem(
                name=item,
                value=(xlen + 1 - idx) * 10,
                itemstyle_opts=opts.ItemStyleOpts(color="#d48265"),
            )
        )

c = (
    Bar()
    .add_xaxis(x)
    .add_yaxis("series0", y, category_gap=0, color=Faker.rand_color())
    .set_global_opts(title_opts=opts.TitleOpts(title="Bar-直方图(颜色区分)"))
    .render("bar_histogram_color.html")
)

再来看结果:

[图表]pyecharts模块-柱状图2-LMLPHP

再来看解析:

这段代码使用了Python中的pyecharts模块来创建一个柱状图,并通过Faker模块生成了一些假数据。

首先,导入了需要的模块:

  • opts:包含一些图表配置选项的模块
  • Bar:用于创建柱状图的类
  • Faker:用于生成假数据的类

接下来,使用Faker模块生成了一组假数据,将dogs列表和animal列表相加作为横坐标数据x

x = Faker.dogs + Faker.animal

然后,计算了横坐标数据的长度xlen

xlen = len(x)

接着,通过循环遍历横坐标数据x,根据索引和条件判断来生成纵坐标数据y

y = []
for idx, item in enumerate(x):
    if idx <= xlen / 2:
        y.append(
            opts.BarItem(
                name=item,
                value=(idx + 1) * 10,
                itemstyle_opts=opts.ItemStyleOpts(color="#749f83"),
            )
        )
    else:
        y.append(
            opts.BarItem(
                name=item,
                value=(xlen + 1 - idx) * 10,
                itemstyle_opts=opts.ItemStyleOpts(color="#d48265"),
            )
        )

在循环中,根据索引和条件判断,生成了不同的BarItem对象,并设置了不同的颜色。每个BarItem对象表示一个柱状图的柱子,其中包括了名称、值和样式等信息。

然后,创建了一个Bar对象,并使用add_xaxis方法添加横坐标数据:

c = (
    Bar()
    .add_xaxis(x)
    ...
)

接着,使用add_yaxis方法添加一个纵坐标系列,命名为"series0",并传入之前生成的纵坐标数据y

    .add_yaxis("series0", y, category_gap=0, color=Faker.rand_color())

在这里,设置了柱状图的颜色为随机颜色。

然后,使用set_global_opts方法设置全局选项,这里设置了图表的标题为"Bar-直方图(颜色区分)":

    .set_global_opts(title_opts=opts.TitleOpts(title="Bar-直方图(颜色区分)"))

最后,使用render方法将图表渲染为一个HTML文件,并保存为"bar_histogram_color.html":

    .render("bar_histogram_color.html")

整个过程中,每个方法调用都返回了当前对象,所以可以使用链式调用的方式来依次添加数据和配置。最终,变量c存储了渲染图表的结果。

注:图表资源来源于:
pyecharts-gallery
本站只提供常用图表与其解析

06-03 22:10