GUEST0 pt
クイズ・バイオインフォの森
3. 【python】等高線【matplotlib】

3. 【python】等高線【matplotlib】

目次

1. 基本

subplotを使わない方法

subplotを使う方法

Text
# figure
plt.figure(figsize=(14, 6), dpi=100)
ax = plt.subplot(111)


# plot (ex. bar plot)
bars = []
xs = np.array(range(1, 50 + 1))
data = list(range(50))
plt.bar(xs, data, width=0.2, color='blue')


# text
x, y = 40, 15
plt.text(x, y, '*', fontsize=14)


# title
plt.title(f'BIC score per model')


# x axis config
plt.xticks(n_components_range)
ax.set_xlabel('Number of components')


# y axis config
plt.ylim([BICs.min() * 1.01 - .01 * BICs.max(), BICs.max()])


# legend
ax.legend('BIC')


# show
plt.show()

2. 等高線

関数と実行例は以下です。

Text
def plot_decomposition_with_best_gmm(data, bic_results):
    # to nparray
    xy = np.array(data.iloc[:, :2])


    # unpacking
    best_gmm = bic_results['best_gmm']
    lowest_bic_n_component = bic_results['lowest_bic_n_component']
    lowest_bic_cv_type = bic_results['lowest_bic_cv_type']


    # plot decomsition
    plt.figure(figsize=(14, 10))
    plt.scatter(xy[:, 0], xy[:, 1], s=5, label='Data', color='blue', alpha=0.5)


    # plot cluster centers
    plt.scatter(best_gmm.means_[:, 0], best_gmm.means_[:, 1], marker='o', s=100, label='Means', color='red', edgecolors='black')


    # plot contours
    x_min, x_max = min(xy[:,0]), max(xy[:,0])
    y_min, y_max = min(xy[:,1]), max(xy[:,1])
    x_delta, y_delta = x_max - x_min, y_max - y_min
    x = np.linspace(x_min - 0.05 * x_delta, x_max + 0.05 * x_delta, 100)
    y = np.linspace(y_min - 0.05 * y_delta, y_max + 0.05 * y_delta, 100)
    X_grid, Y_grid = np.meshgrid(x, y)
    Z = -best_gmm.score_samples(np.array([X_grid.ravel(), Y_grid.ravel()]).T)
    Z = Z.reshape(X_grid.shape)
    plt.contour(X_grid, Y_grid, Z, levels=10, linewidths=1, colors='green', linestyles='dashed', alpha=0.5)


    # layout
    plt.xlabel('Axis 1')
    plt.ylabel('Axis 2')
    plt.title(f'Gaussian Mixture Model with {lowest_bic_n_component} components and {lowest_bic_cv_type}')
    plt.legend()
    plt.grid(True)
    plt.show()


plot_decomposition_with_best_gmm(res_pca, bic_results_pca)

広告を取得中...
3. 【python】等高線【matplotlib】 | バイオインフォの森