美文网首页
Python画图&读写csv

Python画图&读写csv

作者: 乘瓠散人 | 来源:发表于2020-04-26 01:04 被阅读0次
设置字体
import matplotlib
# to avoid Type 3 font
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
import matplotlib.pyplot as plt
plt.rc('font', family='Times New Roman')
设置图例
import numpy as np
import os
import matplotlib
# to avoid Type 3 font in pdf
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
import matplotlib.pyplot as plt


if __name__ == "__main__":

    root_dir = 'logs/'

    train = np.load(root_dir + "train_loss.npy")
    t_acc = np.load(root_dir + "train_acc.npy")
    eval = np.load(root_dir + "val_loss.npy")
    e_acc = np.load(root_dir + "val_acc.npy")

    x = np.arange(len(train))

    plt.figure(1)
    plt.plot(x, train, color='r', linewidth=1.0, label='train_loss')
    plt.plot(x, eval, color='b', linewidth=1.0, label='eval_loss')
    plt.xlabel('epochs', fontsize=20)
    plt.ylabel('loss', fontsize=20)
    plt.title('lr=0.0001, hidden_size=100', fontsize=20)
    plt.legend(loc='upper right', fontsize=20)
    plt.tight_layout()
    # plt.savefig(root_dir + 'loss.png')
    plt.savefig(root_dir + 'loss.pdf', dpi=600, format='pdf')

    plt.figure(2)
    plt.plot(x, t_acc, color='r', label='train_acc')
    plt.plot(x, e_acc, color='b', label='eval_acc')
    plt.xlabel('epochs')
    plt.ylabel('accuracy')
    plt.title('lr=0.0001, hidden_size=100')
    plt.legend(loc='upper right')
    plt.savefig(root_dir + 'accuracy.svg', dpi=600, format='svg')

设置坐标轴的范围和刻度
plt.xlim((0, 2100))  # 设置坐标轴范围
plt.xticks(np.arange(0, 2100, 200))  #设置坐标轴刻度
设置坐标轴的精度
import matplotlib.ticker as ticker
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111)
ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2f'))  
Python读写csv文件
import csv
import pickle
import numpy as np


def get_csv():
    with open('test_results.tsv', 'r') as f:
        reader = csv.reader(f, delimiter='\t')
        lines = []
        for line in reader:
            lines.append(line)

    predictions = []
    for (i, line) in enumerate(lines):
        pred = 0
        if line[0] < line[1]:
            pred = 1
        predictions.append(pred)

    with open('new_test.tsv', 'w', newline='') as f:
        writer = csv.writer(f, delimiter='\t')
        writer.writerow(["index", "prediction"])
        for (i, item) in enumerate(predictions):
            writer.writerow([i, item])
matplotlib在图像上画矩形框
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))
    ax1.imshow(image)
    ax1.add_patch(patches.Rectangle((top_left_x1, top_left_y1), width, height, fill=False, edgecolor='red', linewidth=2))
    ax1.add_patch(patches.Rectangle((top_left_x2, top_left_y2), width, height, fill=False, edgecolor='red', linewidth=2))

    ms = ax2.matshow(heatmap)
    ax2.add_patch(patches.Rectangle((top_left_x1, top_left_y1), width, height, fill=False, edgecolor='red', linewidth=2))
    ax2.add_patch(patches.Rectangle((top_left_x2, top_left_y2), width, height, fill=False, edgecolor='red', linewidth=2))
    # disable ticks
    ax1.set_xticks([])
    ax1.set_yticks([])
    ax2.set_xticks([])
    ax2.set_yticks([])
    # additional colorbar
    fig.subplots_adjust(right=0.9)
    rect_bar = [0.92, 0.15, 0.02, 0.7]  # [left, bottom, width, height]
    cbar_ax = fig.add_axes(rect_bar)
    cb = fig.colorbar(ms, cax=cbar_ax)

    plt.savefig('123.png')
    plt.close()
matplotlib画折线图并填充阴影
    fig, ax = plt.subplots()
    ax.plot(orders, diff, color='green')
    ax.fill_between(orders, 0, diff, facecolor='green', alpha=0.3)
    ax.set_xlabel('ratios')
    ax.set_ylabel("difference")
    ax.set_title(arch)
    ax.set_xticks(np.arange(0.1, 1.1, 0.1))
    fig.tight_layout()
    plt.savefig(save_name)
    plt.close()

相关文章

网友评论

      本文标题:Python画图&读写csv

      本文链接:https://www.haomeiwen.com/subject/nrjrwhtx.html