Python数据可视化

 基于asciichartpy

import asciichartpy

data = [1, 2, 3, 4, 5, 4, 3, 2, 1]
chart = asciichartpy.plot(data)
print(chart)

 

基于sparklines

import sparklines

data = [1, 2, 3, 4, 5, 4, 3, 2, 1]
sparkline_str = ''.join(sparklines.sparklines(data))
print(sparkline_str)

 

基于sparkline-nb将曲线插入dataframe

import io
import base64
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display, HTML


def sparkline(data, figsize=(4, 0.25), **kwargs):
    """
    Returns an HTML image tag containing a base64 encoded sparkline style plot
    """
    data = list(data)
    
    fig, ax = plt.subplots(1, 1, figsize=figsize, **kwargs)
    ax.plot(data)
    for k, v in ax.spines.items():
        v.set_visible(False)
    ax.set_xticks([])
    ax.set_yticks([])

    plt.plot(len(data) - 1, data[len(data) - 1], 'r.')

    ax.fill_between(range(len(data)), data, [min(data)]*len(data), alpha=0.1)
    
    img = io.BytesIO()
    plt.savefig(img, format='png')
    img.seek(0)
    plt.close()
    
    # Encode the image in base64
    img_base64 = base64.b64encode(img.read()).decode('utf-8')
    
    return f'<img src="data:image/png;base64,{img_base64}"/>'


if __name__ == "__main__":

    n = 4
    data = [
        ('rand',        np.random.rand(n)), 
        ('randn',       np.random.randn(n)), 
        ('beta',        np.random.beta(2, 1, size=n)),
        ('binomial',    np.random.binomial(3.4, 0.22, size=n)),
        ('exponential', np.random.exponential(size=n)),
        ('geometric',   np.random.geometric(0.5, size=n)),
        ('laplace',     np.random.laplace(size=n))
    ]
    spark = pd.DataFrame(data, columns=['func', 'data'])
    print(spark)

    # map the sparkline function over the data column
    # and store back in the column sparklines
    spark['sparklines'] = spark.data.map(sparkline)
    # _repr_html_ escapes HTML so manually handle the rendering
    HTML(spark.to_html(escape=False))

 

基于xlsxwriter在Excel里插入曲线

import xlsxwriter

wb = xlsxwriter.Workbook('hello.xlsx')
ws = wb.add_worksheet()

data=[12,23,9,17,31,3,7,21,10,15]
ws.write_row('A1', data)
ws.set_column('K:K', 40)
ws.set_row(0, 30)

data=[1,1,-1,-1,-1,1,1,1,-1,-1]
ws.write_row('A5', data)
ws.set_column('K:K', 40)
ws.set_row(4, 30)
ws.add_sparkline('K1', {'range':'Sheet1!A1:J1', 'markers':True})
ws.add_sparkline('K5', {'range':'Sheet1!A5:J5', 'type':'win_loss',
'negative_points':True})

wb.close()
# 更多参数
ws.add_sparkline(idx + 1, offset - 1, {
        'range': data_sheet_loc, 
        'markers': False, 
        'markers_color': 'purple',
        'series_color': 'blue', 
        'high_point': 'red', 
        'high_color': 'red',
        'low_point': 'green', 
        'low_color': 'green'
    }
)

 

基于matplotlib.pyplot先生成png,然后再插入Excel的方法

import os
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
from matplotlib import font_manager
from openpyxl import load_workbook
from openpyxl.drawing.image import Image

def insert_pic(excel_path, pic_path, height):
    if not os.path.exists(excel_path):
        log.error("failed to insert pic because of missing {}".format(excel_path))
        return
    if not os.path.exists(pic_path):
        log.error("failed to insert pic because of missing {}".format(pic_path))
        return
    print(excel_path, pic_path)
    xl = load_workbook(excel_path)
    xl_sheet = xl[xl.sheetnames[0]]
    pos = "B" + str(xl_sheet.max_row + height + 5)
    img = Image(pic_path)
    xl_sheet.add_image(img, pos)
    xl.save(excel_path)
    xl.close()

 

...

 

posted @ 2024-07-01 19:01  lixin[at]hitwh  阅读(6)  评论(0编辑  收藏  举报