Python reads excel file data and draws histogram

Python reads excel file data and draws histogram

import xlrd
import os
import numpy as np
import matplotlib.pyplot as plt
import math

def read_excel(file_path):

    data = {
    
    }

    workBook = xlrd.open_workbook(file_path)
    allSheetNames = workBook.sheet_names()

    for sheet_name in allSheetNames:
        temp_data = {
    
    }
        sheet_content = workBook.sheet_by_name(sheet_name)
        rows = sheet_content.nrows
        for row in range(rows):
            row_data = sheet_content.row_values(row)
            if row == 0:
                temp_data['type'] = row_data[2:]
            else:
                temp_data[row_data[0]] = row_data[2:]

        data[sheet_name] = temp_data
    return data

def show_figure(data, type):

    sheet_content = data[type]
    num_x = np.arange(len(sheet_content['type']))
    fig, ax = plt.subplots()
    width = 0.1
    num_width = 0
    for k in sheet_content:
        if k == 'type':
            continue
        y = sheet_content[k]
        for i in range(len(y)):
            if y[i] == 'null':
                y[i] = 0
        y = [i*100 for i in y]
        ax.bar(num_x + num_width * width, y, width, alpha=1, label=k)
        num_width += 1
    ax.set_xticks(num_x + (num_width - 1) * width / 2)
    ax.set_xticklabels(sheet_content['type'], fontsize=15)
    ax.set_ylabel('MMrTRE [%]', fontsize=15)
    #ax.set_title(type, fontsize=25)
    ax.legend(fontsize=12, ncol=3)
    ax.set_yscale('log')

    plt.yticks(fontsize=15)
    plt.grid()
    plt.show()

if __name__ == '__main__':
    repoRoot = os.path.dirname(os.path.realpath(__file__))
    file_path = os.path.join(repoRoot, 'ANHIR_metric.xlsx')
    data = read_excel(file_path=file_path)

    # show figure
    show_figure(data, 'All')
    show_figure(data, 'Evaluation')

Guess you like

Origin blog.csdn.net/qq_35898332/article/details/113253246