Pyecharts之饼图(Pie)

Pyecharts之饼图(Pie)

from snapshot_selenium import snapshot as driver

from pyecharts import options as opts
from pyecharts.charts import Pie
from pyecharts.render import make_snapshot
from pyecharts.globals import CurrentConfig,NotebookType

CurrentConfig.NOTEBOOK_TYPE=NotebookType.JUPYTER_LAB

一.基本概念

class pyecharts.charts.Pie

class Pie(
    # 初始化配置项,参考 `global_options.InitOpts`
    init_opts: opts.InitOpts = opts.InitOpts()
)

func pyecharts.charts.Pie.add

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

    # 系列数据项,格式为 [(key1, value1), (key2, value2)]
    data_pair: Sequence,

    # 系列 label 颜色
    color: Optional[str] = None,

    # 饼图的半径,数组的第一项是内半径,第二项是外半径
    # 默认设置成百分比,相对于容器高宽中较小的一项的一半
    radius: Optional[Sequence] = None,

    # 饼图的中心(圆心)坐标,数组的第一项是横坐标,第二项是纵坐标
    # 默认设置成百分比,设置成百分比时第一项是相对于容器宽度,第二项是相对于容器高度
    center: Optional[Sequence] = None,

    # 是否展示成南丁格尔图,通过半径区分数据大小,有'radius'和'area'两种模式。
    # radius:扇区圆心角展现数据的百分比,半径展现数据的大小
    # area:所有扇区圆心角相同,仅通过半径展现数据大小
    rosetype: Optional[str] = None,

    # 饼图的扇区是否是顺时针排布。
    is_clockwise: bool = True,

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

    # 提示框组件配置项,参考 `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 import options as opts
from pyecharts.charts import Pie
from pyecharts.faker import Faker

p = (
    Pie()
    .add("", [list(z) for z in zip(Faker.choose(), Faker.values())])
    .set_colors(["blue", "green", "yellow", "red", "pink", "orange", "purple"])
    .set_global_opts(title_opts=opts.TitleOpts(title="Pie-设置颜色"))
    .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
    #.render("pie_set_color.html")
)

#make_snapshot(driver,g.render("gauge.html"),"gauge.png")
p.load_javascript()
p.render_notebook()
import pyecharts.options as opts
from pyecharts.charts import Pie

x_data = ["直接访问", "邮件营销", "联盟广告", "视频广告", "搜索引擎"]
y_data = [335, 310, 274, 235, 400]
data_pair = [list(z) for z in zip(x_data, y_data)]
data_pair.sort(key=lambda x: x[1])

p=(
    Pie(init_opts=opts.InitOpts(width="1000px", height="600px", bg_color="#2c343c"))
    .add(
        series_name="访问来源",
        data_pair=data_pair,
        rosetype="radius",
        radius="55%",
        center=["50%", "50%"],
        label_opts=opts.LabelOpts(is_show=False, position="center"),
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(
            title="Customized Pie",
            pos_left="center",
            pos_top="20",
            title_textstyle_opts=opts.TextStyleOpts(color="#fff"),
        ),
        legend_opts=opts.LegendOpts(is_show=False),
    )
    .set_series_opts(
        tooltip_opts=opts.TooltipOpts(
            trigger="item", formatter="{a} <br/>{b}: {c} ({d}%)"
        ),
        label_opts=opts.LabelOpts(color="rgba(255, 255, 255, 0.3)"),
    )
    #.render("customized_pie.html")
)

#make_snapshot(driver,g.render("gauge.html"),"gauge.png")
p.load_javascript()
p.render_notebook()
from pyecharts import options as opts
from pyecharts.charts import Pie
from pyecharts.faker import Faker

p = (
    Pie()
    .add(
        "",
        [list(z) for z in zip(Faker.choose(), Faker.values())],
        radius=["40%", "55%"],
        label_opts=opts.LabelOpts(
            position="outside",
            formatter="{a|{a}}{abg|}\n{hr|}\n {b|{b}: }{c}  {per|{d}%}  ",
            background_color="#eee",
            border_color="#aaa",
            border_width=1,
            border_radius=4,
            rich={
                "a": {"color": "#999", "lineHeight": 22, "align": "center"},
                "abg": {
                    "backgroundColor": "#e3e3e3",
                    "width": "100%",
                    "align": "right",
                    "height": 22,
                    "borderRadius": [4, 4, 0, 0],
                },
                "hr": {
                    "borderColor": "#aaa",
                    "width": "100%",
                    "borderWidth": 0.5,
                    "height": 0,
                },
                "b": {"fontSize": 16, "lineHeight": 33},
                "per": {
                    "color": "#eee",
                    "backgroundColor": "#334455",
                    "padding": [2, 4],
                    "borderRadius": 2,
                },
            },
        ),
    )
    .set_global_opts(title_opts=opts.TitleOpts(title="Pie-富文本示例"),
                     #legend_opts=opts.LegendOpts(type_="scroll",pos_left="80%",orient="vertical")
    )
    #.render("pie_rich_label.html")
)

#make_snapshot(driver,g.render("gauge.html"),"gauge.png")
p.load_javascript()
p.render_notebook()
from pyecharts import options as opts
from pyecharts.charts import Pie
from pyecharts.faker import Faker

p = (
    Pie()
    .add(
        "",
        [
            list(z)
            for z in zip(
                Faker.choose() + Faker.choose() + Faker.choose(),
                Faker.values() + Faker.values() + Faker.values(),
            )
        ],
        center=["40%", "50%"],
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Pie-Legend 滚动"),
        legend_opts=opts.LegendOpts(type_="scroll", pos_left="80%", orient="vertical"),
    )
    .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
    #.render("pie_scroll_legend.html")
)
#make_snapshot(driver,g.render("gauge.html"),"gauge.png")
p.load_javascript()
p.render_notebook()
from pyecharts import options as opts
from pyecharts.charts import Pie
from pyecharts.commons.utils import JsCode


fn = """
    function(params) {
        if(params.name == '其他')
            return '\\n\\n\\n' + params.name + ' : ' + params.value + '%';
        return params.name + ' : ' + params.value + '%';
    }
    """


def new_label_opts():
    return opts.LabelOpts(formatter=JsCode(fn), position="center")


p = (
    Pie()
    .add(
        "",
        [list(z) for z in zip(["剧情", "其他"], [25, 75])],
        center=["20%", "30%"],
        radius=[60, 80],
        label_opts=new_label_opts(),
    )
    .add(
        "",
        [list(z) for z in zip(["奇幻", "其他"], [24, 76])],
        center=["55%", "30%"],
        radius=[60, 80],
        label_opts=new_label_opts(),
    )
    .add(
        "",
        [list(z) for z in zip(["爱情", "其他"], [14, 86])],
        center=["20%", "70%"],
        radius=[60, 80],
        label_opts=new_label_opts(),
    )
    .add(
        "",
        [list(z) for z in zip(["惊悚", "其他"], [11, 89])],
        center=["55%", "70%"],
        radius=[60, 80],
        label_opts=new_label_opts(),
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Pie-多饼图基本示例"),
        legend_opts=opts.LegendOpts(
            type_="scroll", pos_top="20%", pos_left="80%", orient="vertical"
        ),
    )
    #.render("mutiple_pie.html")
)
p.load_javascript()
p.render_notebook()

三.示例演示

数据具体处理过程链接:去哪儿

1.数据处理与获取

import pandas as pd

data=pd.read_csv("travel2.csv")

import re

def Look(e):
    
    if '万' in e:
        num=re.findall('(.*?)万',e)
        return float(num[0])*10000
    else:
        return float(e)
    
data['浏览次数']=data['浏览量'].apply(Look)
data.drop(['浏览量'],axis=1,inplace=True)
data['浏览次数']=data['浏览次数'].astype(int)
data1=data.head(7)
data.head(7)
地点 短评 出发时间 天数 人均费用 人物 玩法 浏览次数
0 婺源 春天的婺源,油菜花开,宛如一幅诗情画意的水墨画 /2020/04/01 5 3000 三五好友 第一次 美食 9055
1 阿联酋 阿联酋|小狮妹和父母的新年迪拜之旅 /2019/12/10 8 - - - 3860
2 AguadePau 来自《一个女生的古巴独行记》(11日自由行攻略) /2019/09/27 11 20000 独自一人 深度游 美食 摄影 国庆 261
3 建水 云南│我什么也没忘,但有些事只适合收藏 /2019/10/10 8 4000 三五好友 穷游 摄影 古镇 赏秋 国庆 6176
4 日本 日本|东京の72小时 /2019/09/21 8 - - - 12000
5 海宁 海洪宁静,盐潮入官,百里钱塘,春暖花开--驾“浙”观大潮访金庸、赏樱花睡房车 /2020/03/23 2 900 情侣 自驾 赏樱 踏春 清明 22000
6 敦煌 甘青│到远方去,到那个山野苍茫的远方,熟悉的地方没有景色 /2019/05/10 10 3500 三五好友 环游 毕业游 穷游 14000
datas=[list(z) for z in zip(data1["地点"].tolist(),data1["浏览次数"].tolist())]
datas.sort(key=lambda x:x[1])
datas
[['AguadePau', 261],
 ['阿联酋', 3860],
 ['建水', 6176],
 ['婺源', 9055],
 ['日本', 12000],
 ['敦煌', 14000],
 ['海宁', 22000]]

2.展示

import pyecharts.options as opts
from pyecharts.charts import Pie

p=(
    Pie(init_opts=opts.InitOpts(width="1000px", height="600px", bg_color="#2c343c"))
    .add(
        series_name="旅游浏览",
        data_pair=datas,
        rosetype="radius",
        radius="55%",
        center=["50%", "50%"],
        label_opts=opts.LabelOpts(is_show=False, position="center"),
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(
            title="旅游 Pie",
            pos_left="center",
            pos_top="20",
            title_textstyle_opts=opts.TextStyleOpts(color="#fff"),
        ),
        legend_opts=opts.LegendOpts(is_show=False),
    )
    .set_series_opts(
        tooltip_opts=opts.TooltipOpts(
            trigger="item", formatter="{a} <br/>{b}: {c} ({d}%)"
        ),
        label_opts=opts.LabelOpts(color="rgba(255, 255, 255, 0.3)"),
    )
    #.render("customized_pie.html")
)

#make_snapshot(driver,g.render("gauge.html"),"gauge.png")
p.load_javascript()
p.render_notebook()


posted @ 2020-04-03 22:03  LQ6H  阅读(1693)  评论(0编辑  收藏  举报