matplotlib by example

最終更新: 2017-10-25 11:53

CSVの読み込み

#! -*- coding: utf-8 -*-
import csv
import matplotlib.pyplot as plt

x = []
y1 = []
y2 = []
with open('experiment1.csv', 'r') as f:
    reader = csv.reader(f)
    # header = next(reader)

    for row in reader:
        x.append(int(row[0]))
        y1.append(float(row[1]))
        y2.append(float(row[2]))
plt.plot(x, y1, 'or', label="random")
plt.plot(x, y2, 'ob', label="BO")
plt.xlabel("experiment")
plt.ylabel("best score so far")
plt.legend(loc="lower right")
plt.show()

散布図の各点にラベルをつける

https://stackoverflow.com/questions/14432557/matplotlib-scatter-plot-with-different-text-at-each-data-point

#! -*- coding: utf-8 -*-
import csv
import matplotlib.pyplot as plt

name = []
x = []
y = []
with open('data.csv', 'r') as f:
    reader = csv.reader(f)
    # header = next(reader)

    for row in reader:
        name.append(row[0])
        x.append(float(row[1]))
        y.append(float(row[2]))
plt.scatter(x, y)
for i, txt in enumerate(name):
    plt.annotate(txt, (x[i], y[i]))
plt.xlabel("predicted score")
plt.ylabel("actual score")
plt.show()

PCAとの組み合わせ

import csv
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.decomposition import PCA
import numpy as np

train_X = []
train_y = []
with open('train-light.csv', 'r') as f:
    reader = csv.reader(f)
    header = next(reader)
    for row in reader:
        train_X.append([float(r) for r in row[2:89]])
        train_y.append(int(row[90]))

train_X = np.array(train_X)
train_y = np.array(train_y)

pca = PCA(n_components=2)
pca.fit(train_X)

X_pca = pca.transform(train_X)
negative = X_pca[np.where(train_y==0)]
positive = X_pca[np.where(train_y==1)]

plt.scatter(positive[:,0], positive[:,1], color='red', marker='.')
plt.scatter(negative[:,0], negative[:,1], color='blue', marker='x')