Advertisement

基于python的超市历年数据可视化分析

阅读量:

数据可视化分析目录

      • 一、数据描述

        • 1、数据概览
      • 二、数据预处理

        • 0、导入包和数据
    • 1、列名重命名

    • 2、提取数据中时间,方便后续分析绘图

      • 三、数据可视化
        • 1、美国各个地区销售额的分布(地图)
    • 2、各产品类别销售额对比(柱状图)

    • 3、不同客户类别销售额对比(饼图)

    • 4、每月各产品销售额top10榜单

    • 5、销售额、净利润在时间维度的变化(折线图)

    • 6、销售额

一、数据描述

数据集中9994条数据,横跨1237天,
销售额为2,297,200.8603美元,
利润为286,397.0217美元,
他们的库存中有1862件独特的物品,
它们被分为3类,
所有这些物品都在美国4个地区的49个州销售,
来着793位客户的5009个订单。

数据集: Superstore.csv 来源:kaggle

一共21列数据,每一列属性描述如下:

复制代码
    Row ID => 每一行唯一的ID.
    Order ID => 每个客户的唯一订单ID.
    Order Date => 产品的订单日期.
    Ship Date => 产品发货日期.
    Ship Mode=> 客户指定的发货模式.
    Customer ID => 标识每个客户的唯一ID.
    Customer Name => 客户的名称.
    Segment => The segment where the Customer belongs.
    Country => 客户居住的国家.
    City => 客户居住的城市.
    State => 客户所在的州.
    Postal Code => 每个客户的邮政编码.
    Region => “客户”所属地区.
    Product ID => 产品的唯一ID.
    Category => 所订购产品的类别.
    Sub-Category => 所订购产品的子类别.
    Product Name => 产品名称
    Sales =>产品的销售.
    Quantity => 产品数量.
    Discount => 提供折扣.
    Profit => 已发生的利润/亏损.
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
1、数据概览

9994行,21列数据

复制代码
    print(df.info())
    
    
      
    
复制代码
    <class 'pandas.core.frame.DataFrame'>
    RangeIndex: 9994 entries, 0 to 9993
    Data columns (total 21 columns):
     #   Column         Non-Null Count  Dtype  
    ---  ------         --------------  -----  
     0   Row ID         9994 non-null   int64  
     1   Order ID       9994 non-null   object 
     2   Order Date     9994 non-null   object 
     3   Ship Date      9994 non-null   object 
     4   Ship Mode      9994 non-null   object 
     5   Customer ID    9994 non-null   object 
     6   Customer Name  9994 non-null   object 
     7   Segment        9994 non-null   object 
     8   Country        9994 non-null   object 
     9   City           9994 non-null   object 
     10  State          9994 non-null   object 
     11  Postal Code    9994 non-null   int64  
     12  Region         9994 non-null   object 
     13  Product ID     9994 non-null   object 
     14  Category       9994 non-null   object 
     15  Sub-Category   9994 non-null   object 
     16  Product Name   9994 non-null   object 
     17  Sales          9994 non-null   float64
     18  Quantity       9994 non-null   int64  
     19  Discount       9994 non-null   float64
     20  Profit         9994 non-null   float64
    dtypes: float64(3), int64(3), object(15)
    memory usage: 1.6+ MB
    None
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    

二、数据预处理

0、导入包和数据
复制代码
    import pandas as pd
    from pyecharts.charts import *
    from pyecharts import options as opts
    from pyecharts.commons.utils import JsCode
    
    data = pd.read_csv(r'./data/Superstore.csv')
    
    
      
      
      
      
      
      
    
1、列名重命名

重命名后的列名:

复制代码
    data.columns = ['行ID', '订单ID', '订单日期', '发货日期', '发货方式', '客户ID', '客户名称', '客户类型', '国家', '城市', '州', '邮政编码', '所属区域', '产品ID',
                '产品类别', '产品子类别', '产品名称', '销售额', '产品数量', '提供折扣', '利润/亏损']
    
    
      
      
    
2、提取数据中时间,方便后续分析绘图
复制代码
    data['年份'] = data['订单日期'].apply(lambda x: x[-4:])
    data['日期'] = pd.to_datetime(data['订单日期'], format='%m/%d/%Y')
    data['月份'] = data['日期'].dt.month
    data['年-月'] = data['年份'].astype('str') + '-' + data['月份'].astype('str')
    
    
      
      
      
      
    

三、数据可视化

1、美国各个地区销售额的分布(地图)

包含:Order_Date Sales Quantity Profit year month

复制代码
    usa_sale = data[['州', '销售额']].groupby('州').sum().round(2).reset_index()
    print(usa_sale.head())
    
    
    def echarts_map(province, data, title='主标题', subtitle='副标题', label='图例'):
    """
    province:传入省份List
    data:传入各省对应的数据List
    title:主标题
    subtitle:副标题
    label:图例
    """
    map_ = Map(
        init_opts=opts.InitOpts(
            bg_color='#080b30'
            theme='dark'
            width='980px'
            height='700px'
        )
    )
    map_.add(label, [list(i) for i in zip(province, data)],
             maptype='美国'
             )
    map_.set_global_opts(
    
        title_opts=opts.TitleOpts(
            title=title
            subtitle=subtitle
            pos_left='center'
            title_textstyle_opts=dict(color='#fff') 
        legend_opts=opts.LegendOpts(
            is_show=True 
            pos_left='right'
            pos_top='3%'
            orient='horizontal' 
        ),
        visualmap_opts=opts.VisualMapOpts(max_=int(max(data)), is_piecewise=False)
    )
    return map_.render(title + '-' + subtitle + '.html')
    
    
    echarts_map(usa_sale['州'].tolist(), usa_sale['销售额'].tolist(), title='美国各地区销售额分布'
            , subtitle='销售额分布地图', label='销售额')
    
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
请添加图片描述
2、各产品类别销售额对比(柱状图)
复制代码
    pro_category = data[['产品类别', '销售额', '利润/亏损']].groupby('产品类别').sum().round(2).reset_index()
    pro_category.head()
    
    
    def echarts_bar(x, y, y2, title='主标题', subtitle='副标题', label='图例', label2='图例2'):
    """
    x: 函数传入x轴标签数据
    y:函数传入y轴数据
    title:主标题
    subtitle:副标题
    label:图例
    """
    bar = Bar(
        init_opts=opts.InitOpts(
            bg_color='#080b30'
            theme='dark'
            width='900px'
            height='600px'  
        )
    )
    bar.add_xaxis(x)
    bar.add_yaxis(label, y,
                  label_opts=opts.LabelOpts(is_show=True)
                  , category_gap="70%"  
                  , yaxis_index=0
                  )
    bar.add_yaxis(label2, y2,
                  label_opts=opts.LabelOpts(is_show=True) 
                  , category_gap="70%"  
                  , yaxis_index=1
                  )
    bar.set_series_opts( 
        label_opts=opts.LabelOpts(
            is_show=True,
            position='top'
            font_size=15,
            color='white',
            font_weight='bolder'
            font_style='oblique'
        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)
                    """
                )
                'shadowBlur': 15
                "barBorderRadius": [100, 100, 100, 100]
                "shadowColor": "#0EEEF9"
                'shadowOffsetY': 2,
                'shadowOffsetX': 2
            }
        }
    )
    bar.set_global_opts(
    
        title_opts=opts.TitleOpts(
            title=title
            subtitle=subtitle
            pos_left='center'
            title_textstyle_opts=dict(color='#fff') 
        ),
     
        legend_opts=opts.LegendOpts(
            is_show=True
            pos_left='right'
            pos_top='3%'
            orient='horizontal' 
        ),
        tooltip_opts=opts.TooltipOpts(
            is_show=True
            trigger='axis'
            is_show_content=True,
            trigger_on='mousemove|click'
            axis_pointer_type='cross'
        ),
        yaxis_opts=opts.AxisOpts(
            is_show=True,
            splitline_opts=opts.SplitLineOpts(is_show=False), 
            axistick_opts=opts.AxisTickOpts(is_show=False),  
            axislabel_opts=opts.LabelOpts(  
                font_size=13, 
                font_weight='bolder' 
            ),
        )
        xaxis_opts=opts.AxisOpts(
            boundary_gap=True
            axistick_opts=opts.AxisTickOpts(is_show=True)
            splitline_opts=opts.SplitLineOpts(is_show=False)
            axisline_opts=opts.AxisLineOpts(is_show=True)
            axislabel_opts=opts.LabelOpts( 
                font_size=13
                font_weight='bolder' 
            ),
        ),
    )
    bar.extend_axis(yaxis=opts.AxisOpts())
    return bar.render(title + '-' + subtitle + '.html')
    
    
    echarts_bar(pro_category['产品类别'].tolist(), pro_category['销售额'].tolist(),
            pro_category['利润/亏损'].tolist(), title='不同产品类别销售额对比', subtitle='销售额对比柱状图',
            label='销售额', label2='利润')
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
请添加图片描述
3、不同客户类别销售额对比(饼图)
复制代码
    customer_sale = data[['客户类型', '销售额', '利润/亏损']].groupby('客户类型').sum().round(2).reset_index()
    
    
    def echarts_pie(x, y, title='主标题', subtitle='副标题', label='图例'):
    pie = Pie(
        init_opts=opts.InitOpts(
            bg_color='#080b30'
            theme='dark'
            width='900px'
            height='600px'
        )
    )
    pie.add('', [list(z) for z in zip(x, y)])
    pie.set_series_opts(label_opts=opts.LabelOpts(
        formatter="{b}: {c}",
        font_size='15',
        font_style='oblique',
        font_weight='bolder'
    )
    )
    pie.set_global_opts(
    
        title_opts=opts.TitleOpts(
            title=title
            subtitle=subtitle
            pos_left='center'
            title_textstyle_opts=dict(color='white')
            subtitle_textstyle_opts=dict(color='white')
        ),
        legend_opts=opts.LegendOpts(
            is_show=True,
            pos_left='right'
            pos_top='3%', 
            orient='vertical', 
            textstyle_opts=opts.TextStyleOpts(
                color='white', 
                font_size='13', 
                font_weight='bolder', 
            ),
        )
    )
    return pie.render(title + '-' + subtitle + '.html')
    
    
    echarts_pie(customer_sale['客户类型'], customer_sale['销售额'], title='不同客户类别销售额对比', subtitle=' ', label='销售额')
    echarts_pie(customer_sale['客户类型'], customer_sale['利润/亏损'], title='不同客户类别利润对比', subtitle=' ', label='利润/亏损')
    
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
请添加图片描述
4、每月各产品销售额top10榜单
复制代码
    month_lis = data.sort_values(by='日期')['年-月'].unique().tolist()
    month_sale = []
    for i in month_lis:
    month_data = data[data['年-月'] == i][['产品名称', '销售额']].groupby(['产品名称']). \
                     sum().round(2).reset_index().sort_values(by='销售额', ascending=False)[:10]
    month_data = month_data.sort_values(by='销售额', ascending=True)
      
    month_sale.append(month_data)
    
    
    
    def echart_line(x, y, title='主标题', subtitle='副标题', label='图例'):
    tl = Timeline(
        init_opts=opts.InitOpts(
            bg_color='#080b30'
            theme='dark'
            width='1200px'
            height='700px' 
        )
    )
    tl.add_schema(
        is_auto_play=True
        play_interval=1500
        is_loop_play=True
    )
    
    for i, data1 in zip(x, y):
        day = i
        bar = Bar(
            init_opts=opts.InitOpts(
                bg_color='#080b30'
                theme='dark'
                width='1200px'
                height='700px'
            )
        )
        bar.add_xaxis(data1.iloc[:, 0].tolist())
        bar.add_yaxis(
            label,
            data1.iloc[:, 1].round(2).tolist(),
            category_gap="40%"
        )
        bar.reversal_axis()
        bar.set_series_opts( 
            label_opts=opts.LabelOpts(
                is_show=True,
                position="right",
                font_style='oblique',
                font_weight='bolder',
                font_size='13',
    
            ),
            itemstyle_opts={
                "normal": {
                    "color": JsCode(
                        """new echarts.graphic.LinearGradient(1, 0, 0, 0, [{
                            offset: 0,color: 'rgba(0, 244, 255, 1)'}
                            ,{offset: 1,color: 'rgba(0, 77, 167, 1)'}], false)
                        """
                    )
                    'shadowBlur': 8
                    "barBorderRadius": [100, 100, 100, 100]
                    "shadowColor": "#0EEEF9"
                    'shadowOffsetY': 6,
                    'shadowOffsetX': 6, 
                }
            }
        )
        bar.set_global_opts(
         
            title_opts=opts.TitleOpts(
                title=title, 
                subtitle=subtitle, 
                pos_left='center', 
                title_textstyle_opts=dict(color='white'), 
                subtitle_textstyle_opts=dict(color='#white')
            ),
            legend_opts=opts.LegendOpts(
                is_show=True, 
                pos_left='right', 
                pos_top='3%',  
                orient='vertical', 
                textstyle_opts=opts.TextStyleOpts(
                    color='white', 
                    font_size='13', 
                    font_weight='bolder', 
                    font_style='oblique',
                ),
            ),
            tooltip_opts=opts.TooltipOpts(
                is_show=True, 
                trigger='axis',  
                is_show_content=True,
                trigger_on='mousemove|click',  
                axis_pointer_type='cross',  
              
            ),
            yaxis_opts=opts.AxisOpts(
                is_show=True,
                splitline_opts=opts.SplitLineOpts(is_show=False), 
                axistick_opts=opts.AxisTickOpts(is_show=False), 
                axislabel_opts=opts.LabelOpts( 
                    font_size=13, 
                    font_weight='bolder' 
                ),
            ), 
            xaxis_opts=opts.AxisOpts(
                boundary_gap=True,  axistick_opts=opts.AxisTickOpts(is_show=True), 
                splitline_opts=opts.SplitLineOpts(is_show=False), 
                axisline_opts=opts.AxisLineOpts(is_show=True), 
                axislabel_opts=opts.LabelOpts(  
                    font_size=13,  
                    font_weight='bolder',                  ),
            ),
        )
    
        tl.add(bar, day)
    
    return tl.render(title + '-' + subtitle + '.html')
    
    
    
    echart_line(month_lis, month_sale, title='每月各产品销售额top10榜单', subtitle=' ', label='销售额')
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
请添加图片描述
5、销售额、净利润在时间维度的变化(折线图)
复制代码
    sale_data = data.sort_values(by='日期')[['年份', '日期', '销售额', '利润/亏损']]. \
    groupby(['年份', '日期']).sum().round(2).reset_index()
    year_lis = sale_data['年份'].unique().tolist()
    sale_data1 = sale_data[sale_data['年份'] == '2014']
    sale_data2 = sale_data[sale_data['年份'] == '2015']
    sale_data3 = sale_data[sale_data['年份'] == '2016']
    sale_data4 = sale_data[sale_data['年份'] == '2017']
    sale_data_lis = [sale_data1, sale_data2, sale_data3, sale_data4]
    print(sale_data4.head())
    
    
    def echarts_two_line(x, y, title='主标题', subtitle='副标题', label='图例', label2='图例2'):
    """
    x: 函数传入x轴table数据
    y:函数传入y轴dataframe集合
    title:主标题
    subtitle:副标题
    label:图例
    """
    tab = Tab()
    for table, data in zip(x, y):
        line1 = Line(
            init_opts=opts.InitOpts(
                bg_color='#080b30',  # 设置背景颜色
                theme='dark',  # 设置主题
                width='1200px',  # 设置图的宽度
                height='700px'  # 设置图的高度
            )
        )
        line1.add_xaxis(data['日期'].tolist())
        line1.extend_axis(yaxis=opts.AxisOpts())  # 添加一条Y轴
        line1.add_yaxis(
            label,
            data['销售额'].tolist(),
            yaxis_index=0,
            is_symbol_show=False,  # 是否显示数据标签点
            is_smooth=True,  # 设置曲线平滑
            label_opts=opts.LabelOpts(
                is_show=True,  # 是否显示数据
            ),
            # 线条粗细阴影设置
            linestyle_opts={
                "normal": {
                    "color": "#E47085",  # 线条颜色
                    "shadowColor": '#E4708560',  # 阴影颜色和不透明度
                    "shadowBlur": 8,  # 阴影虚化大小
                    "shadowOffsetY": 20,  # 阴影y偏移量
                    "shadowOffsetX": 20,  # 阴影x偏移量
                    "width": 7  # 线条粗细
                },
            },
        )
        line1.set_global_opts(
            # 标题设置
            title_opts=opts.TitleOpts(
                title=title,  # 主标题
                subtitle=subtitle,  # 副标题
                pos_left='center',  # 标题展示位置
                title_textstyle_opts=dict(color='white'),  # 设置标题字体颜色
                subtitle_textstyle_opts=dict(color='white')
            ),
            # 图例设置
            legend_opts=opts.LegendOpts(
                is_show=True,  # 是否显示图例
                pos_left='right',  # 图例显示位置
                pos_top='3%',  # 图例距离顶部的距离
                orient='horizontal',  # 图例水平布局
                textstyle_opts=opts.TextStyleOpts(
                    color='white',  # 颜色
                    font_size='13',  # 字体大小
                    font_weight='bolder',  # 加粗
                ),
            ),
            tooltip_opts=opts.TooltipOpts(
                is_show=True,  # 是否使用提示框
                trigger='axis',  # 触发类型
                is_show_content=True,
                trigger_on='mousemove|click',  # 触发条件,点击或者悬停均可出发
                axis_pointer_type='cross',  # 指示器类型,鼠标移动到图表区可以查看效果
                # formatter = '{a}<br>{b}:{c}人'  # 文本内容
            ),
            datazoom_opts=opts.DataZoomOpts(
                range_start=0,  # 开始范围
                range_end=25,  # 结束范围
                # orient='vertical',  # 设置为垂直布局
                type_='slider',  # slider形式
                is_zoom_lock=False,  # 锁定区域大小
                # pos_left='1%'  # 设置位置
            ),
            yaxis_opts=opts.AxisOpts(
                is_show=True,
                splitline_opts=opts.SplitLineOpts(is_show=False),  # 分割线
                axistick_opts=opts.AxisTickOpts(is_show=False),  # 刻度不显示
                axislabel_opts=opts.LabelOpts(  # 坐标轴标签配置
                    font_size=13,  # 字体大小
                    font_weight='bolder'  # 字重
                ),
            ),  # 关闭Y轴显示
            xaxis_opts=opts.AxisOpts(
                boundary_gap=False,  # 两边不显示间隔
                axistick_opts=opts.AxisTickOpts(is_show=True),  # 刻度不显示
                splitline_opts=opts.SplitLineOpts(is_show=False),  # 分割线不显示
                axisline_opts=opts.AxisLineOpts(is_show=True),  # 轴不显示
                axislabel_opts=opts.LabelOpts(  # 坐标轴标签配置
                    font_size=13,  # 字体大小
                    font_weight='bolder'  # 字重
                ),
            ),
        )
    
        # 新建一个折线图Line
        line2 = Line()
        line2.add_xaxis(data['日期'].tolist())
        # 将line数据通过yaxis_index指向后添加的Y轴
        # line2.extend_axis(yaxis=opts.AxisOpts())
        line2.add_yaxis(
            label2,
            data['利润/亏损'].tolist(),
            yaxis_index=0,
            is_symbol_show=False,  # 是否显示数据标签点
            is_smooth=True,  # 设置曲线平滑
            label_opts=opts.LabelOpts(
                is_show=True,  # 是否显示数据
            ),
            # 线条粗细阴影设置
            linestyle_opts={
                "normal": {
                    "color": "#44B2BE",  # 线条颜色
                    "shadowColor": '#44B2BE60',  # 阴影颜色和不透明度
                    "shadowBlur": 8,  # 阴影虚化大小
                    "shadowOffsetY": 20,  # 阴影y偏移量
                    "shadowOffsetX": 20,  # 阴影x偏移量
                    "width": 7  # 线条粗细
                },
            },
        )
        line1.overlap(line2)
    
        tab.add(line1, table)
    
    return tab.render(title + '-' + subtitle + '.html')
    
    
    echarts_two_line(year_lis, sale_data_lis, title='销售额、利润在时间维度的变化', subtitle=' ',
                 label='销售额', label2='利润/亏损')
    
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
请添加图片描述
6、销售额
复制代码
    sale_sum = int(data['销售额'].sum())
    num_count = int(data['产品数量'].sum())
    profit_sum = int(data['利润/亏损'].sum())
    print(profit_sum)
    
    
    def big_data(title='主标题', subtitle='副标题'):
    c = Pie(
        init_opts=opts.InitOpts(
            chart_id=1,
            bg_color='#080b30',
            theme='dark',
            width='300px',
            height='300px',
        )
    )
    c.set_global_opts(
        title_opts=opts.TitleOpts(
            title=title,
            subtitle=subtitle,
            title_textstyle_opts=opts.TextStyleOpts(
                font_size=36,
                color='#FFFFFF',
            ),
            pos_left='center',
            pos_top='middle'
        )
    )
    return c.render(str(title) + '-' + subtitle + '.html')
    
    
    big_data(title=sale_sum, subtitle='销售额')
    
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
在这里插入图片描述

全部评论 (0)

还没有任何评论哟~