def plot_importance(names, model, savefig=True):
featureNames = numpy.array(names)
featureImportance = model.feature_importances_
featureImportance = featureImportance / featureImportance.max()
sorted_idx = numpy.argsort(featureImportance)
barPos = numpy.arange(sorted_idx.shape[0]) + .5
plot.barh(barPos, featureImportance[sorted_idx], align='center')
plot.yticks(barPos, featureNames[sorted_idx])
plot.xlabel('Variable Importance')
plot.subplots_adjust(left=0.2, right=0.9, top=0.9, bottom=0.1)
if savefig:
dt_ = datetime.datetime.now().strftime('%d%b%y_%H%M')
plt.savefig("../graphs/featureImportance_" + dt_ + ".png")
plot.show()
# Plot prediction save the graph with a timestamp
python类subplots_adjust()的实例源码
def setMargins(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None):
"""
Tune the subplot layout via the meanings (and suggested defaults) are::
left = 0.125 # the left side of the subplots of the figure
right = 0.9 # the right side of the subplots of the figure
bottom = 0.1 # the bottom of the subplots of the figure
top = 0.9 # the top of the subplots of the figure
wspace = 0.2 # the amount of width reserved for blank space between subplots
hspace = 0.2 # the amount of height reserved for white space between subplots
The actual defaults are controlled by the rc file
"""
plt.subplots_adjust(left, bottom, right, top, wspace, hspace)
plt.draw_if_interactive()
def resetplot():
import matplotlib
import pylab as plt
kw = {}
for p in ['bottom', 'top', 'left', 'right', 'hspace', 'wspace']:
kw[p] = matplotlib.rcParams['figure.subplot.' + p]
plt.subplots_adjust(**kw)
def plotaffinegrid(affines, exag=1e3, affineOnly=True, R=0.025, tpre='', bboxes=None):
import pylab as plt
NR = 3
NC = int(ceil(len(affines)/3.))
#R = 0.025 # 1.5 arcmin
#for (exag,affonly) in [(1e2, False), (1e3, True), (1e4, True)]:
plt.clf()
for i,aff in enumerate(affines):
plt.subplot(NR, NC, i+1)
dl = aff.refdec - R
dh = aff.refdec + R
rl = aff.refra - R / aff.rascale
rh = aff.refra + R / aff.rascale
RR,DD = np.meshgrid(np.linspace(rl, rh, 11),
np.linspace(dl, dh, 11))
plotaffine(aff, RR.ravel(), DD.ravel(), exag=exag, affineOnly=affineOnly,
doclf=False,
units='dots', width=2, headwidth=2.5, headlength=3, headaxislength=3)
if bboxes is not None:
for bb in bboxes:
plt.plot(*bb, linestyle='-', color='0.5')
plt.plot(*bboxes[i], linestyle='-', color='k')
setRadecAxes(rl,rh,dl,dh)
plt.xlabel('')
plt.ylabel('')
plt.xticks([])
plt.yticks([])
plt.title('field %i' % (i+1))
plt.subplots_adjust(left=0.05, right=0.95, wspace=0.1)
if affineOnly:
tt = tpre + 'Affine part of transformations'
else:
tt = tpre + 'Transformations'
plt.suptitle(tt + ' (x %g)' % exag)
def plot_rels(data, labels=None, colors=None, outfile="rels", latent=None, alpha=0.8, title=''):
ns, n = data.shape
if labels is None:
labels = map(str, range(n))
ncol = 5
nrow = int(np.ceil(float(n * (n - 1) / 2) / ncol))
fig, axs = pylab.subplots(nrow, ncol)
fig.set_size_inches(5 * ncol, 5 * nrow)
pairs = list(combinations(range(n), 2))
if colors is not None:
colors = (colors - np.min(colors)) / (np.max(colors) - np.min(colors))
for ax, pair in zip(axs.flat, pairs):
diff_x = max(data[:, pair[0]]) - min(data[:, pair[0]])
diff_y = max(data[:, pair[1]]) - min(data[:, pair[1]])
ax.set_xlim([min(data[:, pair[0]]) - 0.05 * diff_x, max(data[:, pair[0]]) + 0.05 * diff_x])
ax.set_ylim([min(data[:, pair[1]]) - 0.05 * diff_y, max(data[:, pair[1]]) + 0.05 * diff_y])
ax.scatter(data[:, pair[0]], data[:, pair[1]], c=colors, cmap=pylab.get_cmap("jet"),
marker='.', alpha=alpha, edgecolors='none', vmin=0, vmax=1)
ax.set_xlabel(shorten(labels[pair[0]]))
ax.set_ylabel(shorten(labels[pair[1]]))
for ax in axs.flat[axs.size - 1:len(pairs) - 1:-1]:
ax.scatter(data[:, 0], data[:, 1], marker='.')
fig.suptitle(title, fontsize=16)
pylab.rcParams['font.size'] = 12 #6
# pylab.draw()
# fig.set_tight_layout(True)
pylab.tight_layout()
pylab.subplots_adjust(top=0.95)
for ax in axs.flat[axs.size - 1:len(pairs) - 1:-1]:
ax.set_visible(False)
filename = outfile + '.png'
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
fig.savefig(outfile + '.png')
pylab.close('all')
return True
# Hierarchical graph visualization utilities
def allplot(xb,yb,bins=30,fig=1,xlabel='x',ylabel='y'):
"""
Input:
X,Y : objects referring to the variables produced by PyMC that you want
to analyze. Example: X=M.theta, Y=M.slope.
Inherited from Tommy LE BLANC's code at astroplotlib|STSCI.
"""
#X,Y=xb.trace(),yb.trace()
X,Y=xb,yb
#pylab.rcParams.update({'font.size': fontsize})
fig=pylab.figure(fig)
pylab.clf()
gs = pylab.GridSpec(2, 2, width_ratios=[3,1], height_ratios=[1,3], wspace=0.07, hspace=0.07)
scat=pylab.subplot(gs[2])
histx=pylab.subplot(gs[0], sharex=scat)
histy=pylab.subplot(gs[3], sharey=scat)
#scat=fig.add_subplot(2,2,3)
#histx=fig.add_subplot(2,2,1, sharex=scat)
#histy=fig.add_subplot(2,2,4, sharey=scat)
# Scatter plot
scat.plot(X, Y,linestyle='none', marker='o', color='green', mec='green',alpha=.2, zorder=-99)
gkde = scipy.stats.gaussian_kde([X, Y])
x,y = numpy.mgrid[X.min():X.max():(X.max()-X.min())/25.,Y.min():Y.max():(Y.max()-Y.min())/25.]
z = numpy.array(gkde.evaluate([x.flatten(), y.flatten()])).reshape(x.shape)
scat.contour(x, y, z, linewidths=2)
scat.set_xlabel(xlabel)
scat.set_ylabel(ylabel)
# X-axis histogram
histx.hist(X, bins, histtype='stepfilled')
pylab.setp(histx.get_xticklabels(), visible=False) # no X label
#histx.xaxis.set_major_formatter(pylab.NullFormatter()) # no X label
# Y-axis histogram
histy.hist(Y, bins, histtype='stepfilled', orientation='horizontal')
pylab.setp(histy.get_yticklabels(), visible=False) # no Y label
#histy.yaxis.set_major_formatter(pylab.NullFormatter()) # no Y label
#pylab.minorticks_on()
#pylab.subplots_adjust(hspace=0.1)
#pylab.subplots_adjust(wspace=0.1)
pylab.draw()
pylab.show()