python-pygal畫圖


pygal是個非常簡單且功能豐富的py畫圖包,折線圖、柱狀圖、餅圖等常見和不常見的圖像都可輕松實現。
下面將介紹安裝方法,解決中文字體問題、Linux系統亂碼問題,輸出PNG文件問題

基礎操作:

安裝

pip install pygal
文檔特別詳細:
http://www.pygal.org/en/stable/documentation/index.html
如下為官網折線圖實例:

line_chart = pygal.Line()
line_chart.title = 'Browser usage evolution (in %)'
line_chart.x_labels = map(str, range(2002, 2013))
line_chart.add('Firefox', [None, None,    0, 16.6,   25,   31, 36.4, 45.5, 46.3, 42.8, 37.1])
line_chart.add('Chrome',  [None, None, None, None, None, None,    0,  3.9, 10.8, 23.8, 35.3])
line_chart.add('IE',      [85.8, 84.6, 84.7, 74.5,   66, 58.6, 54.7, 44.8, 36.2, 26.6, 20.1])
line_chart.add('Others',  [14.2, 15.4, 15.3,  8.9,    9, 10.4,  8.9,  5.8,  6.7,  6.8,  7.5])
chart.render()  # Return the svg as bytes

image.png

基礎方法

  1. 設置x軸數據:line_chart.x_labels
  2. y軸數據:line_chart.add
  3. 繪圖:line_chart.render()
  4. 保存輸出:
    bytes:chart.render() # Return the svg as bytes
    svg文件:chart.render_to_file('/tmp/chart.svg')
    png圖片:chart.render_to_png('/tmp/chart.png')

字符亂碼問題

依賴安裝

pygal對輸出圖片,及中文不夠友好,需要引入其他依賴包。

pip install webencodings
pip install tinycss2
pip install defusedxml
pip install cssselect2
pip install cairocffi
pip install CairoSVG

如果是linux環境安裝cairo容易失敗,可以下載對應的系統包進行安裝:
https://launchpad.net/ubuntu/+source/pycairo/
我的ubuntu環境下載的:
python3-cairo_1.16.2-1_amd64.deb
安裝:dpkg -i python3-cairo_1.16.2-1_amd64.deb

linux系統亂碼解決

linux系統上輸出 png會有亂碼:
解決:windows的 C:\Windows\Fonts 下的微軟雅黑.ttf文件copy到 linux的/usr/share/fonts目錄

如下為我的一段代碼,將字體改成微軟,同時輸出png:

#####################
# 折線圖:
# 兼容linux 系統 png文字亂碼:
#   windows C:\Windows\Fonts 下的微軟雅黑.ttf文件copy到 linux/usr/share/fonts目錄
#####################

import pygal
import cairo
from pygal.style import Style
from datetime import datetime
colors_dict = {
        1:'#009688',  #
        2:'#F44336',  #
        3:'#3F51B5',  #
        }
def draw_line(data, x_label, y_title, title,colors_list):
    colors = []
    for idx in colors_list:
        if idx in colors_dict:
            colors.append(colors_dict[idx])
        else:
            colors.append(colors_dict[1])
    colors = tuple(colors)
    custom_style = Style(
      background='#FFFFFF',
      plot_background='#FFFFFF',
      value_background='rgba(229, 229, 229, 1)',
      foreground='rgba(0, 0, 0, .87)',
      foreground_strong='rgba(0, 0, 0, 1)',
      foreground_subtle='rgba(0, 0, 0, .54)',

      # Monospaced font is highly encouraged
      font_family=(
      '"微軟雅黑","華文細黑",Arial, Helvetica, sans-serif'),

      label_font_family=None,
      major_label_font_family=None,
      value_font_family=None,
      value_label_font_family=None,
      tooltip_font_family=None,
      title_font_family=None,
      legend_font_family=None,
      no_data_font_family=None,

      label_font_size=20,
      major_label_font_size=20,
      value_font_size=20,
      value_label_font_size=20,
      tooltip_font_size=14,
      title_font_size=30,
      legend_font_size=16,
      no_data_font_size=64,

      # Guide line dash array style
      guide_stroke_dasharray='6,1',
      major_guide_stroke_dasharray='6,1',

      opacity='.7',
      opacity_hover='.8',

      stroke_opacity='.8',
      stroke_opacity_hover='.9',

      transition='150ms',
      colors=colors,
      value_colors=(),
      ci_colors=())

    chart = pygal.Line(fill=True, style=custom_style,title=title,y_title=y_title,
                           x_label_rotation=20, show_legend=False,width=1600,print_values=True,
                            print_zeroes=False, print_values_position='top',
                           show_minor_x_labels=False)
    chart.x_labels = x_label
    chart.x_labels_major = x_label[::5]
    for i in data:
        chart.add(i[0], i[1])
    return chart

if __name__=="__main__":
    data = [('IE', [85.8, 84.6, 84.7, 74.5, 66, 58.6, 54.7, 44.8, 36.2, 26.6, 20.1])]
    x_label = ['2019-07-07', '2019-07-08', '2019-07-12', '2019-07-14', '2019-07-15','2019-07-16', '2019-07-17', '2019-07-18', '2019-07-19', '2019-07-20', '2019-07-21']
    print(x_label)
    y_title = "嘿嘿嘿"
    title = "哈哈哈哈"
    save_path = 'test.png'
    chart = draw_line(data, x_label, y_title, title,[1])
    chart.render_to_png(save_path)


免責聲明!

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



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