在python中每行使用不同数量的子图进行子绘图

时间:2017-09-26 20:57:48

标签: python plot

同样,我对python很新。下面我提供我的代码(用于分类与特征选择),而不是数据,因为它是相当高的维度,但我相信这个问题与数据无关。我的问题是双重的:我想要所有子图的轴标签,我想知道如何在每个子图的子图可以不同的情况下进行子图(我有14个子图,当前有三行):

import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.model_selection import StratifiedKFold
from sklearn.feature_selection import RFECV
from sklearn.datasets import make_classification
from sklearn import preprocessing
import scipy.io as sio
import numpy as np
import os

allData = sio.loadmat('Alldatav2.mat')
allFeatures = allData['featuresAll2']

# loop over subjects
n_subject = [0,1,2,3,4,5,6,7,8,9,10,11,12,13]

fig, axs = plt.subplots(3,5,figsize=(15, 6))
plt.xlabel("Number of features selected")
plt.ylabel("Cross validation score (nb of correct classifications)")
fig.subplots_adjust()
axs = axs.ravel()

for i, j in zip(n_subject, range(15)):
    #print("For Subject : ", i+1)
    y = allData['labels']
    X = allFeatures[i*120:(i+1)*120,:]

    svc = SVC(kernel="linear",C=1)
    rfecv = RFECV(estimator=svc, step=1, cv=StratifiedKFold(2),
              scoring='accuracy')
    rfecv.fit(X, y.ravel())


    axs[j].plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_)
plt.show()


# loop over subjects
def mean(numbers):
    return float(sum(numbers)) / max(len(numbers), 1)

n_subject = [0,1,2,3,4,5,6,7,8,9,10,11,12,13]
avg_scores = []

for i in n_subject:
    print("For Subject : ", i+1)
    y = allData['labels']
    X = allFeatures[i*120:(i+1)*120,:]

    svc = SVC(kernel="linear",C=1)
    rfecv = RFECV(estimator=svc, step=1, cv=StratifiedKFold(10),
              scoring='accuracy')
    rfecv.fit(X, y.ravel())
    print("Optimal number of features : %d" % rfecv.n_features_)
    print("Ranking of Features : ", rfecv.ranking_)
    avg_score = rfecv.grid_scores_.max()
    print("Best CV Score : ", avg_score)
    avg_scores.append(avg_score)
    print("------------------------------------------")
print("Average Accuracy over all Subjects : ", mean(avg_scores))

1 个答案:

答案 0 :(得分:1)

对于每个子图的标签,您可以先创建一个包含这些标签的列表。

xlabelList = [xlabel0, xlabel1 ....,xlabel13]
ylabelList = [ylabel0, ylabel1,....,ylabel13]

此外,您不需要为循环定义额外的变量n_subject。对于绘图,我将进行以下更改:

for j in range(14):

    #print("For Subject : ", j+1)
    y = allData['labels']
    X = allFeatures[j*120:(j+1)*120,:]

    svc = SVC(kernel="linear",C=1)
    rfecv = RFECV(estimator=svc, step=1, cv=StratifiedKFold(2),
          scoring='accuracy')
    rfecv.fit(X, y.ravel())

    locInd = np.unravel_index(j, (3,5))    
    axs[locInd].plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_)
    axs[locInd].set_xlabel(xlabelList[j])
    axs[locInd].set_ylabel(ylabelList[j])
plt.show()