本文整理汇总了Python中matplotlib.gridspec方法的典型用法代码示例。如果您正苦于以下问题:Python matplotlib.gridspec方法的具体用法?Python matplotlib.gridspec怎么用?Python matplotlib.gridspec使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib
的用法示例。
在下文中一共展示了matplotlib.gridspec方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: evaluate
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import gridspec [as 别名]
def evaluate(epoch):
samples = generator(fixed_z).cpu().data.numpy()[:64]
fig = plt.figure(figsize=(8, 8))
gs = gridspec.GridSpec(8, 8)
gs.update(wspace=0.05, hspace=0.05)
for i, sample in enumerate(samples):
ax = plt.subplot(gs[i])
plt.axis('off')
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_aspect('equal')
plt.imshow(sample.transpose((1,2,0)) * 0.5 + 0.5)
if not os.path.exists('out/'):
os.makedirs('out/')
plt.savefig('out/{}.png'.format(str(epoch).zfill(3)), bbox_inches='tight')
plt.close(fig)
示例2: __init__
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import gridspec [as 别名]
def __init__(self, *args, **kwargs):
super(NuPICPlotOutput, self).__init__(*args, **kwargs)
self.names = [self.name]
# Turn matplotlib interactive mode on.
plt.ion()
self.dates = []
self.convertedDates = []
self.actualValues = []
self.predictedValues = []
self.actualLines = []
self.predictedLines = []
self.linesInitialized = False
self.graphs = []
plotCount = len(self.names)
plotHeight = max(plotCount * 3, 6)
fig = plt.figure(figsize=(14, plotHeight))
gs = gridspec.GridSpec(plotCount, 1)
for index in range(len(self.names)):
self.graphs.append(fig.add_subplot(gs[index, 0]))
plt.title(self.names[index])
plt.ylabel('Frequency Bucket')
plt.xlabel('Seconds')
plt.tight_layout()
示例3: show_jigsaw
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import gridspec [as 别名]
def show_jigsaw(input_batch, perm, name):
import matplotlib.gridspec as gridspec
fig = plt.figure(figsize=(6, 6))
outer = gridspec.GridSpec(3, 3)
outer.update(wspace=0.05, hspace=0.05)
for i in range(9):
img = input_batch[i, :, :, :].copy()
img[0,0,0] = 1.0
img[0,1,0] = 0.0
ax = plt.subplot(outer[int(perm[i]/3),perm[i]%3])
ax.axis('off')
ax.get_xaxis().set_visible(False) # this removes the ticks and numbers for x axis
ax.get_yaxis().set_visible(False) # this removes the ticks and numbers for y axis
ax.imshow( np.squeeze(img) )
fig.savefig(name, dpi=128, bbox_inches='tight', pad_inches=0.0)
plt.close()
示例4: plot_images
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import gridspec [as 别名]
def plot_images(args, x_sample, dir, file_name, size_x=3, size_y=3):
fig = plt.figure(figsize=(size_x, size_y))
# fig = plt.figure(1)
gs = gridspec.GridSpec(size_x, size_y)
gs.update(wspace=0.05, hspace=0.05)
for i, sample in enumerate(x_sample):
ax = plt.subplot(gs[i])
plt.axis('off')
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_aspect('equal')
sample = sample.reshape((args.input_size[0], args.input_size[1], args.input_size[2]))
sample = sample.swapaxes(0, 2)
sample = sample.swapaxes(0, 1)
if (args.input_type == 'binary') or (args.input_type in ['multinomial'] and args.input_size[0] == 1):
sample = sample[:, :, 0]
plt.imshow(sample, cmap='gray', vmin=0, vmax=1)
else:
plt.imshow(sample)
plt.savefig(dir + file_name + '.png', bbox_inches='tight')
plt.close(fig)
示例5: axpos
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import gridspec [as 别名]
def axpos(self, axpos):
if axpos is None:
self._axpos = axpos
return
if isinstance(axpos, list) or isinstance(axpos, np.ndarray):
axpos = tuple(axpos)
if isinstance(axpos, tuple) and (len(axpos) == 3 or len(axpos) == 6) and np.all(isinstance(ap, int) for ap in axpos):
self._axpos = axpos
elif isinstance(axpos, int) and axpos >= 100 and axpos < 1000:
self._axpos = (int(axpos/100), int(axpos/10 % 10), int(axpos % 10))
elif isinstance(axpos, int) and axpos >= 110011 and axpos < 999999:
self._axpos = tuple([int(ap) for ap in str(axpos)])
else:
raise ValueError("axpos must be of type int or tuple between 100 and 999 (subplot syntax: ncols, nrows, ind) or 110011 and 999999 (gridspec syntax: ncols, nrows, indx, indy, widthx, widthy)")
示例6: _tile_vertical
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import gridspec [as 别名]
def _tile_vertical(imgs, glimpses, boxes, n_objects, fig_size, img_size, colors):
# prepare figure
yy, xx = imgs.shape[0], 1 + n_objects
fig_y, fig_x = fig_size
img_y, img_x = img_size
sy, sx = yy * img_y, n_objects + img_x
gs = gridspec.GridSpec(sy, sx)
fig = plt.figure(figsize=(sx * fig_x, sy * fig_y))
axes = np.empty((yy, xx), dtype=object)
ii = 0
for i in xrange(yy):
axes[i, 0] = plt.subplot(gs[i * img_y:(i + 1) * img_y, :img_x])
for i in xrange(yy):
for j in xrange(1, xx):
axes[i, j] = plt.subplot(gs[i * img_y:(i + 1) * img_y, j + img_x - 1])
# plot
for r in xrange(yy):
axes[r, 0].imshow(imgs[r], 'gray')
for n in xrange(n_objects):
for (k, v), color in izip(boxes.iteritems(), colors):
y, x, h, w = boxes[k]
bbox = Rectangle((x[r, n], y[r, n]), w[r, n], h[r, n],
edgecolor=color, facecolor='none', label=k)
axes[r, 0].add_patch(bbox)
for c in xrange(1, xx):
axes[r, c].imshow(glimpses[r, c - 1], 'gray')
# TODO: improve
len_bbox = len(boxes)
if len_bbox > 1:
x_offset = .25 * len_bbox
axes[-1, 0].legend(bbox_to_anchor=(x_offset, -.75),
ncol=len_bbox, loc='lower center')
return fig, axes
示例7: __init__
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import gridspec [as 别名]
def __init__(self, gridspec, num1, num2=None):
"""
The subplot will occupy the num1-th cell of the given
gridspec. If num2 is provided, the subplot will span between
num1-th cell and num2-th cell.
The index stars from 0.
"""
rows, cols = gridspec.get_geometry()
total = rows*cols
self._gridspec = gridspec
self.num1 = num1
self.num2 = num2
示例8: get_position
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import gridspec [as 别名]
def get_position(self, fig, return_all=False):
"""
update the subplot position from fig.subplotpars
"""
gridspec = self.get_gridspec()
nrows, ncols = gridspec.get_geometry()
figBottoms, figTops, figLefts, figRights = \
gridspec.get_grid_positions(fig)
rowNum, colNum = divmod(self.num1, ncols)
figBottom = figBottoms[rowNum]
figTop = figTops[rowNum]
figLeft = figLefts[colNum]
figRight = figRights[colNum]
if self.num2 is not None:
rowNum2, colNum2 = divmod(self.num2, ncols)
figBottom2 = figBottoms[rowNum2]
figTop2 = figTops[rowNum2]
figLeft2 = figLefts[colNum2]
figRight2 = figRights[colNum2]
figBottom = min(figBottom, figBottom2)
figLeft = min(figLeft, figLeft2)
figTop = max(figTop, figTop2)
figRight = max(figRight, figRight2)
figbox = mtransforms.Bbox.from_extents(figLeft, figBottom,
figRight, figTop)
if return_all:
return figbox, rowNum, colNum, nrows, ncols
else:
return figbox
示例9: get_topmost_subplotspec
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import gridspec [as 别名]
def get_topmost_subplotspec(self):
'get the topmost SubplotSpec instance associated with the subplot'
gridspec = self.get_gridspec()
if hasattr(gridspec, "get_topmost_subplotspec"):
return gridspec.get_topmost_subplotspec()
else:
return self
示例10: subplot2grid
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import gridspec [as 别名]
def subplot2grid(shape, loc, rowspan=1, colspan=1, **kwargs):
"""
Create a subplot in a grid. The grid is specified by *shape*, at
location of *loc*, spanning *rowspan*, *colspan* cells in each
direction. The index for loc is 0-based. ::
subplot2grid(shape, loc, rowspan=1, colspan=1)
is identical to ::
gridspec=GridSpec(shape[0], shape[2])
subplotspec=gridspec.new_subplotspec(loc, rowspan, colspan)
subplot(subplotspec)
"""
fig = gcf()
s1, s2 = shape
subplotspec = GridSpec(s1, s2).new_subplotspec(loc,
rowspan=rowspan,
colspan=colspan)
a = fig.add_subplot(subplotspec, **kwargs)
bbox = a.bbox
byebye = []
for other in fig.axes:
if other==a: continue
if bbox.fully_overlaps(other.bbox):
byebye.append(other)
for ax in byebye: delaxes(ax)
draw_if_interactive()
return a
示例11: __init__
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import gridspec [as 别名]
def __init__(self, *args, **kwargs):
super(NuPICPlotOutput, self).__init__(*args, **kwargs)
# Turn matplotlib interactive mode on.
plt.ion()
self.dates = []
self.convertedDates = []
self.value = []
self.rawValue = []
self.allValues = []
self.allRawValues = []
self.predicted = []
self.anomalyScore = []
self.anomalyLikelihood = []
self.actualLine = None
self.rawLine = None
self.predictedLine = None
self.anomalyScoreLine = None
self.anomalyLikelihoodLine = None
self.linesInitialized = False
self._chartHighlights = []
fig = plt.figure(figsize=(16, 10))
gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])
self._mainGraph = fig.add_subplot(gs[0, 0])
plt.title(self.name)
plt.ylabel('Value')
plt.xlabel('Date')
self._anomalyGraph = fig.add_subplot(gs[1])
plt.ylabel('Percentage')
plt.xlabel('Date')
# Maximizes window
mng = plt.get_current_fig_manager()
mng.resize(800, 600)
plt.tight_layout()
示例12: __init__
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import gridspec [as 别名]
def __init__(self, name, bins, maximize, anomaly_threshold, anomaly_trigger_count):
self.name = name
self.bins = bins
self.anomaly_threshold = anomaly_threshold
self.anomaly_trigger_count = anomaly_trigger_count
# Turn matplotlib interactive mode on.
plt.ion()
self.seconds = []
self.bin_values = {}
self.anomaly_likelihoods = {}
self.bin_lines = {}
self.anomaly_likelihood_lines = {}
self.lines_initialized = False
self._chart_highlights = []
fig = plt.figure(figsize=(16, 10))
gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])
self._mainGraph = fig.add_subplot(gs[0, 0])
plt.title(self.name)
plt.xlabel('Seconds')
self._anomalyGraph = fig.add_subplot(gs[1])
plt.ylabel('Anomalies')
plt.xlabel('Seconds')
# Maximizes window
if maximize:
mng = plt.get_current_fig_manager()
mng.resize(*mng.window.maxsize())
plt.tight_layout()
示例13: create_gridspec
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import gridspec [as 别名]
def create_gridspec(bams, transcript_file, annotation_files, sv_type, read_data):
"""Helper function for creation of a correctly-sized GridSpec instance
"""
# give one axis to display each sample
num_ax = len(bams)
# add another if we are displaying the SV
if sv_type:
num_ax += 1
# add another if a annotation file is given
if transcript_file:
num_ax += 1
if annotation_files:
num_ax += len(annotation_files)
# set the relative sizes for each
ratios = []
if sv_type:
ratios = [1]
for i in range(len(bams)):
ratios.append(len(read_data["all_coverages"][i]) * 3)
if len(read_data["all_coverages"]) > 0:
ratios[-1] = 9
if annotation_files:
ratios += [0.3] * len(annotation_files)
if transcript_file:
ratios.append(2)
return gridspec.GridSpec(num_ax, 1, height_ratios=ratios), num_ax
# }}}
##Annotations/Transcript methods
# {{{def get_plot_annotation_plan(ranges, annotation_file):
示例14: show_blocks
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import gridspec [as 别名]
def show_blocks(directory):
"""!
@brief Show BANG-blocks (leafs only) in data space.
@details BANG-blocks represents grid that was used for clustering process.
@param[in] directory (bang_directory): Directory that was created by BANG algorithm during clustering process.
"""
dimension = len(directory.get_data()[0])
amount_canvases = 1
if dimension > 1:
amount_canvases = int(dimension * (dimension - 1) / 2)
figure = plt.figure()
grid_spec = gridspec.GridSpec(1, amount_canvases)
pairs = list(itertools.combinations(range(dimension), 2))
if len(pairs) == 0: pairs = [(0, 0)]
for index in range(amount_canvases):
ax = figure.add_subplot(grid_spec[index])
bang_visualizer.__draw_blocks(ax, directory.get_leafs(), pairs[index])
bang_visualizer.__draw_two_dimension_data(ax, directory.get_data(), pairs[index])
plt.show()
示例15: show_grid
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import gridspec [as 别名]
def show_grid(cells, data):
"""!
@brief Show CLIQUE blocks as a grid in data space.
@details Each block contains points and according to this density is displayed. CLIQUE grid helps to visualize
grid that was used for clustering process.
@param[in] cells (list): List of cells that is produced by CLIQUE algorithm.
@param[in] data (array_like): Input data that was used for clustering process.
"""
dimension = cells[0].dimensions
amount_canvases = 1
if dimension > 1:
amount_canvases = int(dimension * (dimension - 1) / 2)
figure = plt.figure()
grid_spec = gridspec.GridSpec(1, amount_canvases)
pairs = list(itertools.combinations(range(dimension), 2))
if len(pairs) == 0: pairs = [(0, 0)]
for index in range(amount_canvases):
ax = figure.add_subplot(grid_spec[index])
clique_visualizer.__draw_cells(ax, cells, pairs[index])
clique_visualizer.__draw_two_dimension_data(ax, data, pairs[index])
plt.show()