python实战打卡---day12

  1. pyecharts水球图
    ⽔球图的取值 [0.67, 0.30, 0.15]表⽰下图中的 三个波浪线 ,⼀般代表三个百分⽐:

    from pyecharts import options as opts
    from pyecharts.charts import Liquid, Page
    from pyecharts.globals import SymbolType
    def liquid() -> Liquid:
        c = (
            Liquid()
            .add("lq", [0.67, 0.30, 0.15])
            .set_global_opts(title_opts=opts.TitleOpts(title="Liquid"))
        )
        return c
    liquid().render('C:/jupyter_notebook/venv_env/myhtml/liquid.html')
    
  2. pyecharts饼图

    from pyecharts import options as opts
    from pyecharts.charts import Pie
    from random import randint
    def pie_base() -> Pie:
        c = (
            Pie()
            .add("", [list(z) for z in zip(['宝马', '法拉利', '奔驰', '奥迪', '⼤众',
            '丰⽥', '特斯拉'],
            [randint(1, 20) for _ in range(7)])])
            .set_global_opts(title_opts=opts.TitleOpts(title="Pie-基本⽰例"))
            .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
        )
        return c
    pie_base().render('C:/jupyter_notebook/venv_env/myhtml/pie_pyecharts.html')
    
  3. pyecharts极坐标图

    极坐标表⽰为 (夹⾓,半径) ,如(6,94)表⽰夹⾓为6,半径94的点:

    import random
    from pyecharts import options as opts
    from pyecharts.charts import Page, Polar
    def polar_scatter0() -> Polar:
        data = [(alpha, random.randint(1, 100)) for alpha in range(101)] # r =random.randint(1, 100)
        print(data)
        c = (
            Polar()
            .add("", data, type_="bar", label_opts=opts.LabelOpts(is_show=False))
            .set_global_opts(title_opts=opts.TitleOpts(title="Polar"))
        )
        return c
    polar_scatter0().render('C:/jupyter_notebook/venv_env/myhtml/polar.html')
    
  4. pyecharts词云图

    (“C”,65)表⽰在本次统计中C语⾔出现65次:

    from pyecharts import options as opts
    from pyecharts.charts import Page, WordCloud
    from pyecharts.globals import SymbolType
    words = [
        ("Python", 100),
        ("C++", 80),
        ("Java", 95),
        ("R", 50),
        ("JavaScript", 79),
        ("C", 65)
    ]
    def wordcloud() -> WordCloud:
        c = (
            WordCloud()
            # word_size_range: 单词字体⼤⼩范围
            .add("", words, word_size_range=[20, 100], shape='cardioid')
            .set_global_opts(title_opts=opts.TitleOpts(title="WordCloud"))
        )
        return c
    wordcloud().render('C:/jupyter_notebook/venv_env/myhtml/wordcloud.html')
    
  5. pyecharts系列柱状图

    from pyecharts import options as opts
    from pyecharts.charts import Bar
    from random import randint
    def bar_series() -> Bar:
        c = (
            Bar()
            .add_xaxis(['宝马', '法拉利', '奔驰', '奥迪', '⼤众', '丰⽥', '特斯拉'])
            .add_yaxis("销量", [randint(1, 20) for _ in range(7)])
            .add_yaxis("产量", [randint(1, 20) for _ in range(7)])
            .set_global_opts(title_opts=opts.TitleOpts(title="Bar的主标题",
            subtitle="Bar的副标题"))
        )
        return c
    bar_series().render('C:/jupyter_notebook/venv_env/myhtml/bar_series.html')
    
  6. pyecharts热力图

    热⼒图描述的实际是三维关系,x轴表⽰车型,y轴表⽰国家,每个⾊块的颜⾊值代表销量,颜⾊刻度尺 显⽰在左下⾓,颜⾊越红表⽰销量越⼤。

    import random
    from pyecharts import options as opts
    from pyecharts.charts import HeatMap
    def heatmap_car() -> HeatMap:
        x = ['宝马', '法拉利', '奔驰', '奥迪', '⼤众', '丰⽥', '特斯拉']
        y = ['中国','⽇本','南⾮','澳⼤利亚','阿根廷','阿尔及利亚','法国','意⼤利','加拿⼤']
        value = [[i, j, random.randint(0, 100)]
                    for i in range(len(x)) for j in range(len(y))]
        c = (
            HeatMap()
            .add_xaxis(x)
            .add_yaxis("销量", y, value)
            .set_global_opts(
            title_opts=opts.TitleOpts(title="HeatMap"),
            visualmap_opts=opts.VisualMapOpts(),
            )
        )
        return c
    heatmap_car().render('C:/jupyter_notebook/venv_env/myhtml/heatmap_pyecharts.html')
    
  7. matplotlib绘制动画

    matplotlib是python中最经典的绘图包,⾥⾯ animation模块能绘制动画。

    # 导入模块
    from matplotlib import pyplot as plt
    from matplotlib import animation
    from random import randint, random
    # ⽣成数据, frames_count是帧的个数, data_count每个帧的柱⼦个数
    class Data:
        data_count = 32
        frames_count = 2
        def __init__(self, value):
            self.value = value
            self.color = (0.5, random(), random()) #rgb
        # 造数据
        @classmethod
        def create(cls):
            return [[Data(randint(1, cls.data_count)) for _ in range(cls.data_count)]
                for frame_i in range(cls.frames_count)]
        # 绘制动画: animation.FuncAnimation函数的回调函数的参数 fi表⽰第⼏帧,注意要调⽤axs.cla()清除上⼀帧。
    def draw_chart():
        fig = plt.figure(1, figsize=(16, 9))
        axs = fig.add_subplot(111)
        axs.set_xticks([])
        axs.set_yticks([])
        # ⽣成数据
        frames = Data.create()
        def animate(fi):
            axs.cla() # clear last frame
            axs.set_xticks([])
            axs.set_yticks([])
            return axs.bar(list(range(Data.data_count)), # X
            [d.value for d in frames[fi]], # Y
            1, # width
            color=[d.color for d in frames[fi]] # color
            )
        # 动画展⽰
        anim = animation.FuncAnimation(fig, animate, frames=len(frames))
        plt.show()
    draw_chart()
    
  8. pyecharts绘图属性设置方法

    pyecharts中,y轴如何显⽰在右侧:

    # 这是pyecharts中⼀般的绘图步骤:
    from pyecharts.faker import Faker
    from pyecharts import options as opts
    from pyecharts.charts import Bar
    from pyecharts.commons.utils import JsCode
    def bar_base() -> Bar:
        c = (
        Bar()
            .add_xaxis(Faker.choose())
            .add_yaxis("商家A", Faker.values())
            .set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本⽰例",
            subtitle="我是副标题"))
        )
        return c
    bar_base().render('C:/jupyter_notebook/venv_env/myhtml/bar.html')
    

    那么,如何设置y轴显⽰在右侧,添加⼀⾏代码:

    .set_global_opts(yaxis_opts=opts.AxisOpts(position=‘right’))

    # 这是pyecharts中⼀般的绘图步骤:
    from pyecharts.faker import Faker
    from pyecharts import options as opts
    from pyecharts.charts import Bar
    from pyecharts.commons.utils import JsCode
    def bar_base() -> Bar:
        c = (
        Bar()
            .add_xaxis(Faker.choose())
            .add_yaxis("商家A", Faker.values())
            .set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本⽰例",
            subtitle="我是副标题"))
            .set_global_opts(yaxis_opts=opts.AxisOpts(position='right'))
        )
        return c
    bar_base().render('C:/jupyter_notebook/venv_env/myhtml/bar11.html'
    

    如何锁定这个属性,⾸先应该在set_global_opts函数的参数中找,它⼀共有以下 11个设置参数,它们 位于模块 charts.py:

    title_opts: types.Title = opts.TitleOpts(),
    legend_opts: types.Legend = opts.LegendOpts(),
    tooltip_opts: types.Tooltip = None,
    toolbox_opts: types.Toolbox = None,
    brush_opts: types.Brush = None,
    xaxis_opts: types.Axis = None,
    yaxis_opts: types.Axis = None,
    visualmap_opts: types.VisualMap = None,
    datazoom_opts: types.DataZoom = None,
    graphic_opts: types.Graphic = None,
    axispointer_opts: types.AxisPointer = None

    因为是设置y轴显⽰在右侧,⾃然想到设置参数 yaxis_opts,因为其类型为 types.Axis,所以再进 ⼊ types.py,同时定位到 Axis:

    Axis = Union[opts.AxisOpts, dict, None]
    

    Union是pyecharts中可容纳多个类型的并集列表,也就是Axis可能为 opts.AxisOpt, dict, 或 None 三种类型。查看第⼀个 opts.AxisOpt类,它共定义以下 25个参数:

    type_: Optional[str] = None,
    name: Optional[str] = None,
    is_show: bool = True,
    is_scale: bool = False,
    is_inverse: bool = False,
    name_location: str = “end”,
    name_gap: Numeric = 15,
    name_rotate: Optional[Numeric] = None,
    interval: Optional[Numeric] = None,
    grid_index: Numeric = 0, position: Optional[str] =
    None,
    offset: Numeric = 0,
    split_number: Numeric = 5,
    boundary_gap: Union[str, bool, None] = None,
    min_: Union[Numeric, str, None] = None,
    max_: Union[Numeric, str, None] = None,
    min_interval: Numeric = 0, max_interval: Optional[Numeric]
    = None,
    axisline_opts: Union[AxisLineOpts, dict, None] = None,
    axistick_opts: Union[AxisTickOpts, dict, None] = None,
    axislabel_opts: Union[LabelOpts, dict, None] = None,
    axispointer_opts: Union[AxisPointerOpts, dict, None] = None,
    name_textstyle_opts: Union[TextStyleOpts, dict, None] = None,
    splitarea_opts: Union[SplitAreaOpts, dict, None] = None,
    splitline_opts: Union[SplitLineOpts, dict] = SplitLineOpts(),

  9. pyecharts绘图属性设置方法(下)

    def bar_border_radius():
        c = (
            Bar(init_opts=opts.InitOpts(animation_opts=opts.AnimationOpts(animation_delay=500, animation_easing="cubicOut"),theme=ThemeType.MACARONS))
            .add_xaxis( ["草莓", "芒果", "葡萄", "雪梨", "西⽠", "柠檬", "车厘⼦"])
            .add_yaxis("A",
                Faker.values(),category_gap="50%",markpoint_opts=opts.MarkPointOpts(),is_selected=True)
            .set_series_opts(itemstyle_opts={
        "normal": {
        "color": JsCode("""new echarts.graphic.LinearGradient(0, 0, 0,
        1, [{
        offset: 0,
        color: 'rgba(0, 244, 255, 1)'
        }, {
        offset: 1,
        color: 'rgba(0, 77, 167, 1)'
        }], false)"""),
        "barBorderRadius": [6, 6, 6, 6],
        "shadowColor": 'rgb(0, 160, 221)',
        }}, markpoint_opts=opts.MarkPointOpts(
        data=[
        opts.MarkPointItem(type_="max", name="最⼤值"),
        opts.MarkPointItem(type_="min", name="最⼩值"),
        ]
        ),markline_opts=opts.MarkLineOpts(
        data=[
        opts.MarkLineItem(type_="min", name="最⼩值"),
        opts.MarkLineItem(type_="max", name="最⼤值")
        ]
        ))
        .set_global_opts(title_opts=opts.TitleOpts(title="Bar-参数使⽤例⼦"),
        toolbox_opts=opts.ToolboxOpts(),yaxis_opts=opts.AxisOpts(position="right",name="Y轴"),datazoom_opts=opts.DataZoomOpts(),)
        )
        return c
    bar_border_radius().render()
    
  10. pyecharts原来可以这样快速⼊门(上)

    pyecharts官档介绍-五个特性:

    1)简洁的 API 设计,使⽤如丝滑般流畅,⽀持链式调⽤;

    2)囊括了 30+ 种常见图表,应有尽有;

    3)⽀持主流 Notebook 环境,Jupyter Notebook 和 JupyterLab;

    4)可轻松集成⾄ Flask,Django 等主流 Web 框架;

    5)⾼度灵活的配置项,可轻松搭配出精美的图表

    from pyecharts.charts import Bar
    bar = Bar()
    bar.add_xaxis(["衬衫", "⽺⽑衫", "雪纺衫", "裤⼦", "⾼跟鞋", "袜⼦"])
    bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
    # render 会⽣成本地 HTML ⽂件,默认会在当前⽬录⽣成 render.html ⽂件
    # 也可以传⼊路径参数,如 bar.render("mycharts.html")
    bar.render('C:/jupyter_notebook/venv_env/myhtml/bar21.html')
    

    Bar(RectChart)是什么意思:RectChart是Bar的⼦类。

  11. pyecharts原来可以这样快速⼊门(中)

    ⼀切皆options。pyecharts⽤起来很爽的另⼀个重要原因, 参数配置项 封装的⾮常nice,通过定义⼀些列基础的配置组 件,⽐如 global_options.py模块中定义的配置对象有以下 27个

    AngleAxisItem,
    AngleAxisOpts,
    AnimationOpts,
    Axis3DOpts,
    AxisLineOpts,
    AxisOpts,
    AxisPointerOpts,
    AxisTickOpts,
    BrushOpts, CalendarOpts,
    DataZoomOpts,
    Grid3DOpts, GridOpts,
    InitOpts, LegendOpts,
    ParallelAxisOpts,
    ParallelOpts,
    PolarOpts,
    RadarIndicatorItem,
    RadiusAxisItem,
    RadiusAxisOpts,
    SingleAxisOpts,
    TitleOpts,
    ToolBoxFeatureOpts,
    ToolboxOpts, TooltipOpts,
    VisualMapOpts,

  12. pyecharts原来可以这样快速⼊门(下)

    第二个例子

    了解上⾯的配置对象后,再看官档给出的第⼆个例⼦,与第⼀个例⼦相⽐,增加了⼀⾏代码: set_global_opts函数。

    from pyecharts.charts import Bar
    from pyecharts import options as opts
    # V1 版本开始⽀持链式调⽤
    # 你所看到的格式其实是 `black` 格式化以后的效果
    # 可以执⾏ `pip install black` 下载使⽤
    bar = (
    Bar()
        .add_xaxis(["衬衫", "⽺⽑衫", "雪纺衫", "裤⼦", "⾼跟鞋", "袜⼦"])
        .add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
        .set_global_opts(title_opts=opts.TitleOpts(title="主标题", subtitle="副标题"))
    bar.render()
    

    set_global_opts函数在pyecharts中被⾼频使⽤,它定义在底层基础模块 Chart.py中,它是前⾯说 到的 RectChart的⼦类, Bar类的孙⼦类。浏览下函数的参数:

    def set_global_opts(
        self,
        title_opts: types.Title = opts.TitleOpts(),
        legend_opts: types.Legend = opts.LegendOpts(),
        tooltip_opts: types.Tooltip = None,
        toolbox_opts: types.Toolbox = None,
        brush_opts: types.Brush = None,
        xaxis_opts: types.Axis = None,
        yaxis_opts: types.Axis = None,
        visualmap_opts: types.VisualMap = None,
        datazoom_opts: types.DataZoom = None,
        graphic_opts: types.Graphic = None,
        axispointer_opts: types.AxisPointer = None,
        )
    

    以第⼆个参数 title_opts为例,说明 pyecharts中参数赋值的风格。 ⾸先, title_opts是 默认参数 ,默认值为 opts.TitleOpts(),这个对象在上⼀节中,我们提到过, 是 global_options.py模块中定义的 27个配置对象种的⼀个。 其次,pyecharts中为了增强代码可读性,参数的类型都显⽰的给出。此处它的类型为: types.Title. 这是什么类型?它的类型不是 TitleOpts吗?不急,看看Title这个类型的定义:

    Title = Union[opts.TitleOpts, dict]

    原来 Title可能是 opts.TitleOpts, 也可能是python原⽣的 dict. 通过 Union实现的就是这种 类型效 果 。所以这就解释了官档中为什么说也可以使⽤字典配置参数的问题,如下官档:

    # 或者直接使⽤字典参数
    # .set_global_opts(title_opts={"text": "主标题", "subtext": "副标题"})
    )
    

    最后,真正的关于图表的标题相关的属性都被封装到TitleOpts类中,⽐如 title, subtitle属性,查 看源码,TitleOpts对象还有更多属性:

    class TitleOpts(BasicOpts):
        def __init__(
            self,
            title: Optional[str] = None,
            title_link: Optional[str] = None,
            title_target: Optional[str] = None,
            subtitle: Optional[str] = None,
            subtitle_link: Optional[str] = None,
            subtitle_target: Optional[str] = None,
            pos_left: Optional[str] = None,
            pos_right: Optional[str] = None,
            pos_top: Optional[str] = None,
            pos_bottom: Optional[str] = None,
            padding: Union[Sequence, Numeric] = 5,
            item_gap: Numeric = 10,
            title_textstyle_opts: Union[TextStyleOpts, dict, None] = None,
            subtitle_textstyle_opts: Union[TextStyleOpts, dict, None] = None,
        )
    

    OK. 到此跟随⼊门的官方文档,结合两个例⼦实现的背后源码,探讨了:

    1)与包结构组织相关的 init.py;

    2)类的继承关系:Bar->RectChart->Chart;

    3)链式调⽤;

    4)重要的参数配置包 options,以TitleOpts类为例, set_global_opts将它装载到Bar类中实现属性⾃定义。

  13. 1分钟学会画 pairplot 图

seaborn 绘图库,基于 matplotlib 开发,提供更⾼层绘图接⼜。 学习使⽤ seaborn 绘制 pairplot 图 pairplot 图能直观的反映出两两特征间的关系,帮助我们对数据集建⽴初步印象,更好的完成分类和 聚类任务。 使⽤ skearn 导⼊经典的 Iris 数据集,共有 150 条记录,4 个特征,target 有三种不同值。

使⽤ seaborn 绘制 sepal_length, petal_length 两个特征间的关系矩阵:

```python
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import tree
import pandas as pd
iris = load_iris()
df=pd.DataFrame(iris.data, columns=iris.feature_names)
sns.set(style="ticks")
df02 = df.iloc[:,:] # 选择⼀对特征
print(df02)
sns.pairplot(df02)
plt.show()
```

设置颜⾊多显:

```python
import matplotlib.pylab as plt
import seaborn as sns
 
df = sns.load_dataset('iris')
my_dpi=96
plt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)
 
sns.pairplot(df, kind="scatter", hue="species", markers=["o", "s", "D"], palette="Set2")
plt.show()
```

绘制所有特征散点矩阵:

```python
import matplotlib.pylab as plt
import seaborn as sns
 
df = sns.load_dataset('iris')
my_dpi=96
plt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)
 
sns.pairplot(df, kind="scatter", hue="species", plot_kws=dict(s=80, edgecolor="white", linewidth=2.5))
plt.show()
```
第五部分结束!!!!!!!

你可能感兴趣的:(学习笔记,python,开发语言)