用Python pyecharts v1.x 繪制圖形【轉】


關於pyecharts

pyecharts是一個用於生成echart(百度開源的數據可視化javascript庫)圖表的類庫。
pyecharts 分為 v0.5.x 和 v1.x 兩個大版本,版本不兼容,本篇所有的案例基於v1.6.2。

柱狀圖

# 柱狀圖
import random
import pyecharts.options as opts
from pyecharts.charts import Bar
x_vals = ['襯衫', '羊毛衫', '雪紡衫', '褲子', '高跟鞋', '襪子']

bar = (
    Bar()
    .add_xaxis(x_vals)
    .add_yaxis('商家A', [random.randint(10, 100) for _ in range(6)])
    .add_yaxis('商家B', [random.randint(10, 100) for _ in range(6)])
    .add_yaxis('商家C', [random.randint(10, 100) for _ in range(6)])
    .add_yaxis('商家D', [random.randint(10, 100) for _ in range(6)])
    .set_series_opts(label_opts=opts.LabelOpts(is_show=True, font_size=14),
                          markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(y=40, name="達標線=40")]))
    .set_global_opts(title_opts=opts.TitleOpts(title='柱狀圖示例-銷量', subtitle='四個商家'),
                     xaxis_opts=opts.AxisOpts(name='商品'),
                     yaxis_opts=opts.AxisOpts(name='單位:件'))
)
bar.render('柱狀圖.html')

堆疊柱狀圖

# 柱狀堆疊圖
import pyecharts.options as opts
from pyecharts.charts import Bar

goods = ['襯衫', '羊毛衫', '雪紡衫', '褲子', '高跟鞋', '襪子']
bar = (
    Bar()
    .add_xaxis(goods)
    .add_yaxis('商家A', [random.randint(10, 100) for _ in range(6)], stack='stack1')
    .add_yaxis('商家B', [random.randint(10, 100) for _ in range(6)], stack='stack1')
    .add_yaxis('商家C', [random.randint(10, 100) for _ in range(6)], stack='stack1')
    .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    .set_global_opts(title_opts=opts.TitleOpts(title='柱狀堆疊圖示例-商品銷量'),
                     xaxis_opts=opts.AxisOpts(name='品類'),       
                     yaxis_opts=opts.AxisOpts(name='銷量(單位:件)'))
)

bar.render('柱狀堆疊圖.html')

條形圖

# 條形圖
x_vals1 = ['襯衫', '羊毛衫', '雪紡衫', '褲子', '高跟鞋', '襪子']
x_vals2 = ['POLO', '籃球鞋', '羽絨服', '皮鞋', '領帶', '睡衣']
x_vals3 = ['羽毛球服', '羽毛球鞋', '護腕', '護膝', '護踝', '毛巾']
y_vals = [random.randint(10, 100) for _ in range(18)]
bar = Bar().add_xaxis(x_vals1 + x_vals2 + x_vals3)      
bar.add_yaxis('商家A', y_vals, 
              markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_='average'),
                                                opts.MarkPointItem(type_='max'),
                                                opts.MarkPointItem(type_='min')], 
                                                symbol_size=80)
              ) 
bar.set_series_opts(label_opts=opts.LabelOpts(is_show=True, position='right'))
bar.set_global_opts(title_opts=opts.TitleOpts(title='條形圖示例-商品銷量', subtitle='條目較多條形圖比較好看點'))
bar.reversal_axis() #翻轉XY軸,將柱狀圖轉換為條形圖
bar.render('條形圖.html')

直方圖

# 直方圖
# 直方圖
import random
import pyecharts.options as opts
from pyecharts.charts import Bar
x_vals = ['襯衫', '羊毛衫', '雪紡衫', '褲子', '高跟鞋', '襪子']
xlen = len(x_vals)

# 設置成兩種顏色
y_vals = []
for idx, item in enumerate(x_vals):
    if idx % 2 == 0:
        y_vals.append(
            opts.BarItem(
                name = item,
                value = random.randint(10, 100),
                itemstyle_opts = opts.ItemStyleOpts(color="#749f83"),
            )
        )
    else:
        y_vals.append(
            opts.BarItem(
                name = item,
                value = random.randint(10, 100),
                itemstyle_opts = opts.ItemStyleOpts(color="#d48265"),
            )
        )

bar_histogram = (
    Bar()
    .add_xaxis(x_vals)
    .add_yaxis('商家A', y_vals, category_gap=0)
     # .add_yaxis('商家A', [random.randint(10, 100) for _ in range(6)], category_gap=0)
    .set_series_opts(label_opts=opts.LabelOpts(is_show=True, font_size=14))
    .set_global_opts(title_opts=opts.TitleOpts(title='直方圖示例-選擇贈品', subtitle=''),
                     xaxis_opts=opts.AxisOpts(name='贈品類型'),
                     yaxis_opts=opts.AxisOpts(name='選擇相應贈品的人數'))
)
bar_histogram.render('直方圖.html')

帕累托圖(復合圖)

# 帕累托圖--# 左邊縱坐標表示頻數,右邊縱坐標表示頻率.分析線表示累積頻率
import random
from pyecharts import options as opts
from pyecharts.charts import Bar, Line
import pandas as pd

# 隨機顏色, from faker
def rand_color() -> str:
    return random.choice(
        [
            "#c23531",
            "#2f4554",
            "#61a0a8",
            "#d48265",
            "#749f83",
            "#ca8622",
            "#bda29a",
            "#6e7074",
            "#546570",
            "#c4ccd3",
            "#f05b72",
            "#444693",
            "#726930",
            "#b2d235",
            "#6d8346",
            "#ac6767",
            "#1d953f",
            "#6950a1",
        ]
    )

df_origin = pd.DataFrame({'categories':['襯衫', '羊毛衫', '雪紡衫', '褲子', '高跟鞋', '襪子'],'sales': [random.randint(10, 100) for _ in range(6)]})
print(df_origin)
# 按銷量降序排列
df_sorted = df_origin.sort_values(by='sales' , ascending=False)
print(df_sorted)

# 折線圖x軸
x_line_categories = [*range(7)] 
# 折線圖y軸--向下累積頻率
cum_percent = df_sorted['sales'].cumsum() / df_sorted['sales'].sum() * 100
cum_percent = cum_percent.append(pd.Series([0])) # 添加起始頻率0
cum_percent = cum_percent.sort_values(ascending=True)

print(df_sorted.categories.values.tolist()) 
print(cum_percent.values.tolist())
def pareto_bar() -> Bar: 
    line = (
        Line()
        .add_xaxis(x_line_categories)        
        .add_yaxis("累計百分比",
                   cum_percent.values.tolist(),    
                   xaxis_index=1,
                   yaxis_index=1,             # 使用次y坐標軸,即bar中的extend_axis
                   label_opts=opts.LabelOpts(is_show=False),
                   is_smooth=True,
                  )
    )
    
    bar = (
        Bar()
        .add_xaxis(df_sorted.categories.values.tolist())
        .add_yaxis('銷售額', df_sorted.sales.values.tolist(), category_gap=0)
        # .add_yaxis('總額百分比', cum_percent.values.tolist())   
        .extend_axis(xaxis=opts.AxisOpts(is_show=False, position='top')) 
        .extend_axis(yaxis=opts.AxisOpts(axistick_opts=opts.AxisTickOpts(is_inside=True),  # 刻度尺朝內
            axislabel_opts=opts.LabelOpts(formatter='{value}%'), position='right') )
        .set_series_opts(label_opts=opts.LabelOpts(is_show=True, font_size=14))
        .set_global_opts(title_opts=opts.TitleOpts(title='帕累托圖示例-銷售額', subtitle=''),
                             xaxis_opts=opts.AxisOpts(name='商品類型', type_='category'),
                             yaxis_opts=opts.AxisOpts(
                                axislabel_opts=opts.LabelOpts(formatter="{value} 件")
                             )
                         )
    )
    bar.overlap(line)
    return bar


pareto_bar().render('帕累托圖.html')

餅圖

# 餅圖
from pyecharts import options as opts
from pyecharts.charts import Page, Pie

pie = (
    Pie()
    .add('鼠標選中分區后的tip',
         [list(z) for z in zip(['20{}年第{}季'.format(year,season)   
                                        for year in [19, 20]  # count 2                                        
                                                for season in range(1,5)] # count 2
                ,[random.randint(2, 10) for _ in range(8)])]) # count 8
    .set_series_opts(label_opts=opts.LabelOpts(formatter='{b}: {c}萬套'))
    .set_global_opts(title_opts=opts.TitleOpts(title='餅圖實例-近兩年季度銷售'),
                         legend_opts=opts.LegendOpts(is_show=False))
)
pie.render('餅圖.html')

圓環圖

from pyecharts.charts import Pie
pie = (
    Pie()
    .add(
        '鼠標選中分區后的tip',
        [list(z) for z in zip(['20{}年第{}季'.format(year,season)   
                                    for year in [19, 20]  # count 2                                        
                                            for season in range(1,5)] # count 2
            ,[random.randint(2, 10) for _ in range(8)])],
        radius=['50%', '75%'],          #設置內徑外徑           
        label_opts=opts.LabelOpts(is_show=True)        
    )
    .set_global_opts(title_opts=opts.TitleOpts(title='圓環圖示例-近兩年季度銷售'),
                     legend_opts=opts.LegendOpts(is_show=False))
)
pie.render('圓環圖.html')

玫瑰圖

# 玫瑰圖
from pyecharts.charts import Pie
pie = (
    Pie()
    .add(
        '鼠標選中分區后的tip',
        [list(z) for z in zip(['20{}年第{}季'.format(year,season)   
                                    for year in [19, 20]  # count 2                                        
                                            for season in range(1,5)] # count 2
            ,[random.randint(0, 10) for _ in range(8)])],
        radius=['10%', '75%'],          #設置內徑外徑
        # rosetype='radius' 圓心角展現數據百分比,半徑展現數據大小
        # rosetype='area' 圓心角相同,為通過半徑展現數據大小
        rosetype='radius',             
        label_opts=opts.LabelOpts(is_show=True)        
    )
    .set_global_opts(title_opts=opts.TitleOpts(title='玫瑰圖示例-近兩年季度銷售'),
                     legend_opts=opts.LegendOpts(is_show=False))
)
pie.render('玫瑰圖.html')

折線圖

# 折線圖
import random
import pyecharts.options as opts
from pyecharts.charts import Line
from pyecharts.commons.utils import JsCode
 
line = (
    Line()
    .add_xaxis(['{}月第{}周周賽'.format(y,z) 
                     for y in range(1, 3)  # 1、2月  
                         for z in range(1, 5)])  # 1-4周
    .add_yaxis('A題', [random.randint(10, 20) for _ in range(8)], 
               is_smooth=True, # 平滑
               markpoint_opts=opts.MarkPointOpts(
                           # 使用coord這個屬性設置自定義標記點數值,我這兒隨便寫
                           data=[opts.MarkPointItem(name='自定義標記點',coord=[2,18],value='標注值')]
                       )
               )
    .add_yaxis('B題', [random.randint(5, 20) for _ in range(8)])
    .add_yaxis('C題', [random.randint(5, 20) for _ in range(8)])
    .set_series_opts(label_opts=opts.LabelOpts(
                    formatter=JsCode( # 通過定義JavaScript回調函數自定義標簽
                         "function(params){"
                                "return params.value[1].toString() + '%';}"  # 外層單引號內存雙引號親測不行!
                    )
                ))
    .set_global_opts(xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-30)), # 設置x軸標簽旋轉角度
                     yaxis_opts=opts.AxisOpts(name='AC率', min_=3), 
                     title_opts=opts.TitleOpts(title='折線示例_ACM題目分析'))        
    )

line.render('折線圖.html')

折線面積圖

# 折線面積圖
import random
import pyecharts.options as opts
from pyecharts.charts import Line
from pyecharts.commons.utils import JsCode
 
line = (
    Line()
    .add_xaxis(['{}月第{}周周賽'.format(y,z) 
                     for y in range(1, 3)  # 1、2月  
                         for z in range(1, 5)])  # 1-4周
    .add_yaxis('蔡隊', 
               [random.randint(10, 20) for _ in range(8)], 
               is_symbol_show=False,         
               areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
               markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_='average', name='均值'),
                                                   opts.MarkPointItem(type_='max', name='最大值'),
                                                   opts.MarkPointItem(type_='min', name='最小值')], 
                                                   symbol_size=50)           
               )
    .add_yaxis('旺神', 
               [random.randint(6, 20) for _ in range(8)], 
               is_smooth=True, 
               is_symbol_show=False,
               areastyle_opts=opts.AreaStyleOpts(opacity=0.5)
               )
    .set_global_opts(xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-30)), # 設置x軸標簽旋轉角度
                     yaxis_opts=opts.AxisOpts(name='完成積分', min_=5), 
                     title_opts=opts.TitleOpts(title='折線面積圖示例_周賽分析'))        
    )

line.render('折線面積圖.html')

散點圖

# 散點圖
from pyecharts.charts import Scatter
from pyecharts import options as opts
from pyecharts.commons.utils import JsCode
import pandas as pd

def scatter_simple() -> Scatter:
    # 數據源
    df = pd.DataFrame({'AC':[21,22,23,24,28,30,34,35,40,44,45],  # 刷題數
                       'ACB':[140,120,380,120,200,190,160,300,300,400,500],
                       '姓名':['小軍','NIL','假冒NOI','小白','弱剛','曉雷','竄天','雲雲','依圖','蔡隊','旺神',]})
    # inplace=True:不創建新的對象,直接對原始對象進行修改
    # 升序
    df.sort_values('AC', inplace=True, ascending=True)  
    
    c = (
        Scatter()
        .add_xaxis(df.AC.values.tolist())
        .add_yaxis(
            '刷題_能力_姓名',
            df[['ACB','姓名']].values.tolist(),
            label_opts=opts.LabelOpts(
                formatter=JsCode(
                    'function(params){return params.value[2];}' #通過定義JavaScript回調函數自定義標簽
                )
            )
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(title='散點圖示例--ACM集訓隊隊員能力'),
            xaxis_opts=opts.AxisOpts(name='AC(刷題數)', type_='value', min_=20),  #x軸從20開始,原點不為0
            yaxis_opts=opts.AxisOpts(name='ACB(能力值)', min_=100),  # y軸起始點的值
            legend_opts=opts.LegendOpts(is_show=True)
        )
    )
    return c
scatter_simple().render('散點圖.html')

雷達圖

# 雷達圖
import random
from pyecharts import options as opts
from pyecharts.charts import Page, Radar
def radar_simple() -> Radar:
    c = (
        Radar()
        .add_schema(
            # 各項的max_值可以不同
            schema=[
                opts.RadarIndicatorItem(name='計算幾何學', max_=100),
                opts.RadarIndicatorItem(name='動態規划', max_=100),
                opts.RadarIndicatorItem(name='圖論', max_=100),
                opts.RadarIndicatorItem(name='搜索', max_=100),
                opts.RadarIndicatorItem(name='模擬', max_=100),
                opts.RadarIndicatorItem(name='數論', max_=100),
            ]
        )
        .add('旺神', [[random.randint(10, 101) for _ in range(6)]],           
             color='red',           
             areastyle_opts = opts.AreaStyleOpts(  #設置填充的屬性
                 opacity = 0.5,                  
                 color='red'                     
         ),)
        .add('蔡隊', [[random.randint(10, 101) for _ in range(6)]],
             color='blue',
             areastyle_opts = opts.AreaStyleOpts(
                 opacity = 0.5,#透明度
                 color='blue'
         ),)
        .set_series_opts(label_opts=opts.LabelOpts(is_show=True))
        .set_global_opts(title_opts=opts.TitleOpts(title='雷達圖示例-ACM集訓隊隊員能力'))
    )
    return c
radar_simple().render('雷達圖.html')

箱線圖

# 箱線圖--描述離散程度
from pyecharts import options as opts
from pyecharts.charts import Boxplot
def boxpolt_base() -> Boxplot:
    v_sophomore = [
        [1.1, 2.2, 2.6, 3.2, 3.7, 4.2, 4.7, 4.7, 5.5, 6.3, 8.0],
        [2.5, 2.5, 2.8, 3.2, 3.7, 4.2, 4.7, 4.7, 5.5, 6.3, 7.0]
    ]
    v_junior = [
        [3.6, 3.7, 4.7, 4.9, 5.1, 5.2, 5.3, 5.4, 5.7, 5.8, 5.8],
        [3.6, 3.7, 4.7, 4.9, 5.1, 5.2, 5.3, 5.4, 5.7, 5.8, 5.8]
    ]
    # 最小值,下四分位數,中位數、上四分位數、最大值
    # [min, Q1, median (or Q2), Q3, max]
    c = (
        Boxplot()
        .add_xaxis(['寒假作業','暑假作業'])
        .add_yaxis('大二隊員', Boxplot.prepare_data(v_sophomore))
        .add_yaxis('大三隊員', Boxplot.prepare_data(v_junior))
        .set_series_opts(label_opts=opts.LabelOpts(is_show=True))
        .set_global_opts(title_opts=opts.TitleOpts(title='ACM集訓隊祖傳練習完成時長離散度'),
                         xaxis_opts=opts.AxisOpts(name='單位:小時'), 
                         legend_opts=opts.LegendOpts(is_show=True))
        .reversal_axis() #翻轉XY軸
    )
    return c

boxpolt_base().render('箱線圖.html')

詞雲圖

# 詞雲圖
from pyecharts import options as opts
from pyecharts.charts import WordCloud
from pyecharts.globals import SymbolType

words = [
    ('背包問題', 10000),
    ('大整數', 6181),
    ('Karatsuba乘法算法', 4386),
    ('窮舉搜索', 4055),
    ('傅里葉變換', 2467),
    ('狀態樹遍歷', 2244),
    ('剪枝', 1868),
    ('Gale-shapley', 1484),
    ('最大匹配與匈牙利算法', 1112),
    ('線索模型', 865),
    ('關鍵路徑算法', 847),
    ('最小二乘法曲線擬合', 582),
    ('二分逼近法', 555),
    ('牛頓迭代法', 550),
    ('Bresenham算法', 462),
    ('粒子群優化', 366),
    ('Dijkstra', 360),
    ('A*算法', 282),
    ('負極大極搜索算法', 273),
    ('估值函數', 265)
]
def wordcloud_base() -> WordCloud:
    c = (
        WordCloud()
        .add("", words, word_size_range=[20, 100], shape=SymbolType.ROUND_RECT)
        .set_global_opts(title_opts=opts.TitleOpts(title='WordCloud示例-OJ搜索關鍵字'))
    )
    return c
wordcloud_base().render('詞雲圖.html')

 

轉自

(3條消息)用Python pyecharts v1.x 繪制圖形(一):柱狀圖、柱狀堆疊圖、條形圖、直方圖、帕累托圖、餅圖、圓環圖、玫瑰圖_Python_shineych的專欄-CSDN博客: https://blog.csdn.net/shineych/article/details/104204330

(3條消息)用Python pyecharts v1.x 繪制圖形(二):折線圖、折線面積圖、散點圖、雷達圖、箱線圖、詞雲圖_Python_shineych的專欄-CSDN博客: https://blog.csdn.net/shineych/article/details/104225239


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM