def plot_counts(counts, gene_type):
"""Plot expression counts. Return a Figure object"""
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
fig = plt.figure(figsize=((50 + len(counts) * 5) / 25.4, 210/25.4))
matplotlib.rcParams.update({'font.size': 14})
ax = fig.gca()
ax.set_title('{} gene usage'.format(gene_type))
ax.set_xlabel('{} gene'.format(gene_type))
ax.set_ylabel('Count')
ax.set_xticks(np.arange(len(counts)) + 0.5)
ax.set_xticklabels(counts.index, rotation='vertical')
ax.grid(axis='x')
ax.set_xlim((-0.25, len(counts)))
ax.bar(np.arange(len(counts)), counts['count'])
fig.set_tight_layout(True)
return fig
python类pyplot()的实例源码
def visualize(self, zv, path):
self.ax1.clear()
self.ax2.clear()
z, v = zv
if path:
np.save(path + '/trajectory.npy', z)
z = np.reshape(z, [-1, 2])
self.ax1.hist2d(z[:, 0], z[:, 1], bins=400)
self.ax1.set(xlim=self.xlim(), ylim=self.ylim())
v = np.reshape(v, [-1, 2])
self.ax2.hist2d(v[:, 0], v[:, 1], bins=400)
self.ax2.set(xlim=self.xlim(), ylim=self.ylim())
if self.display:
import matplotlib.pyplot as plt
plt.show()
plt.pause(0.1)
elif path:
self.fig.savefig(path + '/visualize.png')
def test_cluster_matrix_average():
import utils
import basc
import matplotlib.pyplot as plt
blobs = generate_blobs()
ism = utils.individual_stability_matrix(blobs, 100, 3)
y_predict = utils.cluster_timeseries(blobs, 3, similarity_metric = 'correlation', affinity_threshold=0.0)
cluster_voxel_scores, K_mask = utils.cluster_matrix_average(ism, y_predict)
plt.imshow(K_mask)
#%% TEST BASC.PY
#Remaining Tests to write:
#Join_group_stability
#cluster_selection
#individual_group_clustered_maps
#ndarray_to_vol
def plot_tsne(z_mu, classes, name):
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
model_tsne = TSNE(n_components=2, random_state=0)
z_states = z_mu.data.cpu().numpy()
z_embed = model_tsne.fit_transform(z_states)
classes = classes.data.cpu().numpy()
fig666 = plt.figure()
for ic in range(10):
ind_vec = np.zeros_like(classes)
ind_vec[:, ic] = 1
ind_class = classes[:, ic] == 1
color = plt.cm.Set1(ic)
plt.scatter(z_embed[ind_class, 0], z_embed[ind_class, 1], s=10, color=color)
plt.title("Latent Variable T-SNE per Class")
fig666.savefig('./vae_results/'+str(name)+'_embedding_'+str(ic)+'.png')
fig666.savefig('./vae_results/'+str(name)+'_embedding.png')
def save_plot(niters, loss, args):
print('Saving training loss-iteration figure...')
try:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
name = 'Train-{}_hs-{}_lr-{}_bs-{}'.format(args.train_file, args.hs,
args.lr, args.batch_size)
plt.title(name)
plt.plot(niters, loss)
plt.xlabel('iteration')
plt.ylabel('loss')
plt.savefig(name + '.jpg')
print('{} saved!'.format(name + '.jpg'))
except ImportError:
print('matplotlib not installed and no figure is saved.')
def saveAttention(input_sentence, attentions, outpath):
# Set up figure with colorbar
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
fig = plt.figure(figsize=(24,10), )
ax = fig.add_subplot(111)
cax = ax.matshow(attentions.cpu().numpy(), cmap='bone')
fig.colorbar(cax)
if input_sentence:
# Set up axes
ax.set_yticklabels([' '] + list(input_sentence) + [' '])
# Show label at every tick
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
plt.tight_layout()
plt.savefig(outpath)
plt.close('all')
def heatmap(data,ax,xlabel=None,ylabel=None,xticklabels=None,yticklabels=None,title=None,fontsize=12):
'''
??matplotlib.pyplot.pcolor?????
?????(pc,ax)???pc????matplotlib.pyplot.colorbar??????mappable?
'''
pc=ax.pcolor(data,cmap=plt.cm.Blues)
if xlabel is not None:
ax.set_xlabel(xlabel,fontsize=fontsize)
if ylabel is not None:
ax.set_ylabel(ylabel,fontsize=fontsize)
ax.set_xticks(np.arange(data.shape[1])+0.5,minor=False)
if xticklabels is not None:
ax.set_xticklabels(xticklabels,minor=False,fontsize=fontsize)
ax.set_yticks(np.arange(data.shape[0])+0.5,minor=False)
if yticklabels is not None:
ax.set_yticklabels(yticklabels,minor=False,fontsize=fontsize)
if title is not None:
ax.set_title(title,fontsize=fontsize)
return pc,ax
#????X?Y????
dtopotools_horiz_okada_and_1d.py 文件源码
项目:finite_volume_seismic_model
作者: cjvogl
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def plot_dZ_contours(x, y, dZ, axes=None, dZ_interval=0.5, verbose=False,
fig_kwargs={}):
r"""For plotting seafloor deformation dZ"""
import matplotlib.pyplot as plt
dZ_max = max(dZ.max(), -dZ.min()) + dZ_interval
clines1 = numpy.arange(dZ_interval, dZ_max, dZ_interval)
clines = list(-numpy.flipud(clines1)) + list(clines1)
# Create axes if needed
if axes is None:
fig = plt.figure(**fig_kwargs)
axes = fig.add_subplot(111)
if len(clines) > 0:
if verbose:
print "Plotting contour lines at: ",clines
axes.contour(x, y, dZ, clines, colors='k')
else:
print "No contours to plot"
return axes
dtopotools_horiz_okada_and_1d.py 文件源码
项目:finite_volume_seismic_model
作者: cjvogl
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def plot_dZ_contours(x, y, dZ, axes=None, dZ_interval=0.5, verbose=False,
fig_kwargs={}):
r"""For plotting seafloor deformation dZ"""
import matplotlib.pyplot as plt
dZ_max = max(dZ.max(), -dZ.min()) + dZ_interval
clines1 = numpy.arange(dZ_interval, dZ_max, dZ_interval)
clines = list(-numpy.flipud(clines1)) + list(clines1)
# Create axes if needed
if axes is None:
fig = plt.figure(**fig_kwargs)
axes = fig.add_subplot(111)
if len(clines) > 0:
if verbose:
print "Plotting contour lines at: ",clines
axes.contour(x, y, dZ, clines, colors='k')
else:
print "No contours to plot"
return axes
def ensure_pyplot(self):
"""
Ensures that pyplot has been imported into the embedded IPython shell.
Also, makes sure to set the backend appropriately if not set already.
"""
# We are here if the @figure pseudo decorator was used. Thus, it's
# possible that we could be here even if python_mplbackend were set to
# `None`. That's also strange and perhaps worthy of raising an
# exception, but for now, we just set the backend to 'agg'.
if not self._pyplot_imported:
if 'matplotlib.backends' not in sys.modules:
# Then ipython_matplotlib was set to None but there was a
# call to the @figure decorator (and ipython_execlines did
# not set a backend).
#raise Exception("No backend was set, but @figure was used!")
import matplotlib
matplotlib.use('agg')
# Always import pyplot into embedded shell.
self.process_input_line('import matplotlib.pyplot as plt',
store_history=False)
self._pyplot_imported = True
def ensure_pyplot(self):
"""
Ensures that pyplot has been imported into the embedded IPython shell.
Also, makes sure to set the backend appropriately if not set already.
"""
# We are here if the @figure pseudo decorator was used. Thus, it's
# possible that we could be here even if python_mplbackend were set to
# `None`. That's also strange and perhaps worthy of raising an
# exception, but for now, we just set the backend to 'agg'.
if not self._pyplot_imported:
if 'matplotlib.backends' not in sys.modules:
# Then ipython_matplotlib was set to None but there was a
# call to the @figure decorator (and ipython_execlines did
# not set a backend).
#raise Exception("No backend was set, but @figure was used!")
import matplotlib
matplotlib.use('agg')
# Always import pyplot into embedded shell.
self.process_input_line('import matplotlib.pyplot as plt',
store_history=False)
self._pyplot_imported = True
def activate_matplotlib(backend):
"""Activate the given backend and set interactive to True."""
import matplotlib
matplotlib.interactive(True)
# Matplotlib had a bug where even switch_backend could not force
# the rcParam to update. This needs to be set *before* the module
# magic of switch_backend().
matplotlib.rcParams['backend'] = backend
import matplotlib.pyplot
matplotlib.pyplot.switch_backend(backend)
# This must be imported last in the matplotlib series, after
# backend/interactivity choices have been made
import matplotlib.pyplot as plt
plt.show._needmain = False
# We need to detect at runtime whether show() is called by the user.
# For this, we wrap it into a decorator which adds a 'called' flag.
plt.draw_if_interactive = flag_calls(plt.draw_if_interactive)
def plot_attention(attention_matrix: np.ndarray, source_tokens: List[str], target_tokens: List[str], filename: str):
"""
Uses matplotlib for creating a visualization of the attention matrix.
:param attention_matrix: The attention matrix.
:param source_tokens: A list of source tokens.
:param target_tokens: A list of target tokens.
:param filename: The file to which the attention visualization will be written to.
"""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
assert attention_matrix.shape[0] == len(target_tokens)
plt.imshow(attention_matrix.transpose(), interpolation="nearest", cmap="Greys")
plt.xlabel("target")
plt.ylabel("source")
plt.gca().set_xticks([i for i in range(0, len(target_tokens))])
plt.gca().set_yticks([i for i in range(0, len(source_tokens))])
plt.gca().set_xticklabels(target_tokens, rotation='vertical')
plt.gca().set_yticklabels(source_tokens)
plt.tight_layout()
plt.savefig(filename)
logger.info("Saved alignment visualization to " + filename)
def _store_as_pdf(self, filename: str, fig_width: float, fig_height: float) -> str:
"""
Stores the current figure in a pdf file.
:param filename: name of the pdf file
:param fig_width: width of the figure in cm
:param fig_height: height of the figure in cm
:warning: modifies the current figure
"""
import matplotlib.pyplot as plt
if not filename.endswith(".pdf"):
filename += ".pdf"
self.reset_plt()
self._latexify(fig_width, fig_height)
try:
plt.tight_layout()
except ValueError:
pass
self._format_axes(plt.gca())
plt.savefig(filename)
self.reset_plt()
return os.path.realpath(filename)
def boxplot(self, fig_width: Number, fig_height: Number = None):
"""
Creates a (horizontal) box plot comparing all single object for a given property.
:param fig_width: width of the figure in cm
:param fig_height: height of the figure in cm, if None it is calculated from the figure width using the
aesthetic ratio
"""
import seaborn as sns
import matplotlib.pyplot as plt
self.reset_plt()
if fig_height is None:
fig_height = self._height_for_width(fig_width)
self._fig = plt.figure(figsize=self._fig_size_cm_to_inch(fig_width, fig_height))
df = self.get_data_frame()
sns.boxplot(data=df, orient="h")
def run(self, fig):
"""
Run the exporter on the given figure
Parmeters
---------
fig : matplotlib.Figure instance
The figure to export
"""
# Calling savefig executes the draw() command, putting elements
# in the correct place.
fig.savefig(io.BytesIO(), format='png', dpi=fig.dpi)
if self.close_mpl:
import matplotlib.pyplot as plt
plt.close(fig)
self.crawl_fig(fig)
def test_viz():
"""Test viz."""
import matplotlib.pyplot as plt
events = mne.find_events(raw)
picks = mne.pick_channels(raw.info['ch_names'],
['MEG 2443', 'MEG 2442', 'MEG 2441'])
epochs = mne.Epochs(raw, events, picks=picks, baseline=(None, 0),
reject=None, preload=True,
event_id={'1': 1, '2': 2, '3': 3, '4': 4})
bad_epochs_idx = [0, 1, 3]
n_epochs, n_channels, _ = epochs.get_data().shape
fix_log = np.zeros((n_epochs, n_channels))
print(bad_epochs_idx)
plot_epochs(epochs, bad_epochs_idx=bad_epochs_idx, fix_log=fix_log)
plot_epochs(epochs, bad_epochs_idx=bad_epochs_idx)
plot_epochs(epochs, fix_log=fix_log)
assert_raises(ValueError, plot_epochs, epochs[:2],
bad_epochs_idx=bad_epochs_idx, fix_log=fix_log)
plt.close('all')
def set_matplotlib_defaults(plt, style='ggplot'):
"""Set publication quality defaults for matplotlib.
Parameters
----------
plt : instance of matplotlib.pyplot
The plt instance.
"""
import matplotlib
matplotlib.style.use(style)
fontsize = 17
params = {'axes.labelsize': fontsize + 2,
'text.fontsize': fontsize,
'legend.fontsize': fontsize,
'xtick.labelsize': fontsize,
'ytick.labelsize': fontsize,
'axes.titlesize': fontsize + 2}
plt.rcParams.update(params)
def plot(dims, sequence, factorization):
import matplotlib
matplotlib.use('Agg') # NOQA
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("darkgrid")
plt.ylabel("Speed improvement")
plt.xlabel("Size of embedding layers")
plt.title("Fitting speed (1.0 = no change)")
plt.xscale('log')
plt.plot(dims,
1.0 / sequence,
label='Sequence model')
plt.plot(dims,
1.0 / factorization,
label='Factorization model')
plt.legend(loc='lower right')
plt.savefig('speed.png')
plt.close()
def scoped_mpl_import():
import matplotlib
matplotlib.rcParams['backend'] = MPL_BACKEND
import matplotlib.pyplot as plt
plt.rcParams['toolbar'] = 'None' # mute matplotlib toolbar
import seaborn as sns
sns.set(style="whitegrid", color_codes=True, font_scale=1.0,
rc={'lines.linewidth': 1.0,
'backend': matplotlib.rcParams['backend']})
palette = sns.color_palette("Blues_d")
palette.reverse()
sns.set_palette(palette)
return (matplotlib, plt, sns)
def save_image(real_data, fake_data, filename):
assert real_data.shape == fake_data.shape
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
plt.scatter(fake_data[:,0], fake_data[:,1], color='red', label='noise (fake, sampled)')
plt.scatter(real_data[:,0], real_data[:,1], color='blue', label='hidden (real, inferred)')
#plt.axis('equal')
plt.legend(loc='upper right', fancybox=True, shadow=True, fontsize=11)
plt.grid(True)
plt.xlim(-5, 5)
plt.ylim(-5, 5)
plt.minorticks_on()
plt.xlabel('x', fontsize=14, color='black')
plt.ylabel('y', fontsize=14, color='black')
plt.title('z samples (of first two dimensions)')
plt.savefig(filename)
plt.close()
def save_image_fake(fake_data, filename):
#import warnings
#warnings.filterwarnings("ignore", category=FutureWarning)
#import numpy as np
#import matplotlib
#matplotlib.use('Agg')
#import matplotlib.pyplot as plt
fig, ax = plt.subplots()
#plt.scatter(real_data[:,0], real_data[:,1], color='blue', label='real')
plt.scatter(fake_data[:,0], fake_data[:,1], color='red', label='fake')
plt.axis('equal')
#plt.legend(loc='upper right', fancybox=True, shadow=True, fontsize=11)
plt.grid(True)
plt.xlim(-25, 25)
plt.ylim(-25, 25)
plt.minorticks_on()
plt.xlabel('x', fontsize=14, color='black')
plt.ylabel('y', fontsize=14, color='black')
#plt.title('Toy dataset')
plt.savefig(filename)
plt.close()
def save_image_real(real_data, filename):
#import warnings
#warnings.filterwarnings("ignore", category=FutureWarning)
#import numpy as np
#import matplotlib
#matplotlib.use('Agg')
#import matplotlib.pyplot as plt
fig, ax = plt.subplots()
plt.scatter(real_data[:,0], real_data[:,1], color='blue', label='real')
#plt.scatter(fake_data[:,0], fake_data[:,1], color='red', label='fake')
plt.axis('equal')
#plt.legend(loc='upper right', fancybox=True, shadow=True, fontsize=11)
plt.grid(True)
plt.xlim(-25, 25)
plt.ylim(-25, 25)
plt.minorticks_on()
plt.xlabel('x', fontsize=14, color='black')
plt.ylabel('y', fontsize=14, color='black')
#plt.title('Toy dataset')
plt.savefig(filename)
plt.close()
def save_image(real_data, fake_data, filename):
#import warnings
#warnings.filterwarnings("ignore", category=FutureWarning)
#import numpy as np
#import matplotlib
#matplotlib.use('Agg')
#import matplotlib.pyplot as plt
fig, ax = plt.subplots()
plt.scatter(real_data[:,0], real_data[:,1], color='blue', label='real')
plt.scatter(fake_data[:,0], fake_data[:,1], color='red', label='fake')
#plt.axis('equal')
plt.legend(loc='upper right', fancybox=True, shadow=True, fontsize=11)
plt.grid(True)
plt.xlim(-25, 25)
plt.ylim(-25, 25)
plt.minorticks_on()
plt.xlabel('x', fontsize=14, color='black')
plt.ylabel('y', fontsize=14, color='black')
plt.title('Toy dataset')
plt.savefig(filename)
plt.close()
def test_idw(self):
import numpy as np
import matplotlib.pyplot as plt
from smt.methods import IDW
xt = np.array([0., 1., 2., 3., 4.])
yt = np.array([0., 1., 1.5, 0.5, 1.0])
sm = IDW(p=2)
sm.set_training_values(xt, yt)
sm.train()
num = 100
x = np.linspace(0., 4., num)
y = sm.predict_values(x)
plt.plot(xt, yt, 'o')
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.legend(['Training data', 'Prediction'])
plt.show()
def test_rbf(self):
import numpy as np
import matplotlib.pyplot as plt
from smt.methods import RBF
xt = np.array([0., 1., 2., 3., 4.])
yt = np.array([0., 1., 1.5, 0.5, 1.0])
sm = RBF(d0=5)
sm.set_training_values(xt, yt)
sm.train()
num = 100
x = np.linspace(0., 4., num)
y = sm.predict_values(x)
plt.plot(xt, yt, 'o')
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.legend(['Training data', 'Prediction'])
plt.show()
def test_rmtb(self):
import numpy as np
import matplotlib.pyplot as plt
from smt.methods import RMTB
xt = np.array([0., 1., 2., 3., 4.])
yt = np.array([0., 1., 1.5, 0.5, 1.0])
xlimits = np.array([[0., 4.]])
sm = RMTB(xlimits=xlimits, order=4, num_ctrl_pts=20, energy_weight=1e-15, regularization_weight=0.)
sm.set_training_values(xt, yt)
sm.train()
num = 100
x = np.linspace(0., 4., num)
y = sm.predict_values(x)
plt.plot(xt, yt, 'o')
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.legend(['Training data', 'Prediction'])
plt.show()
def test_rmtc(self):
import numpy as np
import matplotlib.pyplot as plt
from smt.methods import RMTC
xt = np.array([0., 1., 2., 3., 4.])
yt = np.array([0., 1., 1.5, 0.5, 1.0])
xlimits = np.array([[0., 4.]])
sm = RMTC(xlimits=xlimits, num_elements=20, energy_weight=1e-15, regularization_weight=0.)
sm.set_training_values(xt, yt)
sm.train()
num = 100
x = np.linspace(0., 4., num)
y = sm.predict_values(x)
plt.plot(xt, yt, 'o')
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.legend(['Training data', 'Prediction'])
plt.show()
def test_ls(self):
import numpy as np
import matplotlib.pyplot as plt
from smt.methods import LS
xt = np.array([0., 1., 2., 3., 4.])
yt = np.array([0., 1., 1.5, 0.5, 1.0])
sm = LS()
sm.set_training_values(xt, yt)
sm.train()
num = 100
x = np.linspace(0., 4., num)
y = sm.predict_values(x)
plt.plot(xt, yt, 'o')
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.legend(['Training data', 'Prediction'])
plt.show()
def test_krg(self):
import numpy as np
import matplotlib.pyplot as plt
from smt.methods import KRG
xt = np.array([0., 1., 2., 3., 4.])
yt = np.array([0., 1., 1.5, 0.5, 1.0])
sm = KRG(theta0=[1e-2])
sm.set_training_values(xt, yt)
sm.train()
num = 100
x = np.linspace(0., 4., num)
y = sm.predict_values(x)
plt.plot(xt, yt, 'o')
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.legend(['Training data', 'Prediction'])
plt.show()