def set_xlabel(self, label):
r"""
Allow the user to modify the X-axis title
Defaults to the global value. Fontsize defaults
to 18.
Parameters
----------
x_title: str
The new string for the x-axis.
>>> plot.set_xlabel("H2I Number Density (cm$^{-3}$)")
"""
self._xlabel = label
return self
python类cm()的实例源码
def set_colorbar_label(self, field, label):
r"""
Sets the colorbar label.
Parameters
----------
field: str or tuple
The name of the field to modify the label for.
label: str
The new label
>>> plot.set_colorbar_label("density", "Dark Matter Density (g cm$^{-3}$)")
"""
self._colorbar_label[field] = label
return self
def _cmap_discretize(cmap, N):
"""Return a discrete colormap from the continuous colormap cmap.
cmap: colormap instance, eg. cm.jet.
N: number of colors.
Example
x = resize(arange(100), (5,100))
djet = cmap_discretize(cm.jet, 5)
imshow(x, cmap=djet)
"""
if type(cmap) == str:
cmap = plt.get_cmap(cmap)
colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.)))
colors_rgba = cmap(colors_i)
indices = np.linspace(0, 1., N+1)
cdict = {}
for ki, key in enumerate(('red','green','blue')):
cdict[key] = [(indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki])
for i in range(N+1)]
# Return colormap object.
return mcolors.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)
plotting.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 31
收藏 0
点赞 0
评论 0
def _make_plot(self):
x, y, data, C = self.x, self.y, self.data, self.C
ax = self.axes[0]
# pandas uses colormap, matplotlib uses cmap.
cmap = self.colormap or 'BuGn'
cmap = self.plt.cm.get_cmap(cmap)
cb = self.kwds.pop('colorbar', True)
if C is None:
c_values = None
else:
c_values = data[C].values
ax.hexbin(data[x].values, data[y].values, C=c_values, cmap=cmap,
**self.kwds)
if cb:
img = ax.collections[0]
self.fig.colorbar(img, ax=ax)
def plot_accuracies(self, accuracies, scales=[], mode='train', fig=0):
plt.figure(fig)
plt.clf()
colors = cm.rainbow(np.linspace(0, 1, len(scales)))
l = []
names = [str(sc) for sc in scales]
for i, acc in enumerate(accuracies):
ll, = plt.plot(range(len(acc)), acc, color=colors[i])
l.append(ll)
plt.ylabel('accuracy')
plt.legend(l, names, loc=2, prop={'size': 6})
if mode == 'train':
plt.xlabel('iterations')
else:
plt.xlabel('iterations x 1000')
path = os.path.join(self.path, 'accuracies_{}.png'.format(mode))
plt.savefig(path)
def plot_accuracies(self, accuracies, scales=[], mode='train', fig=0):
plt.figure(fig)
plt.clf()
colors = cm.rainbow(np.linspace(0, 1, len(scales)))
l = []
names = [str(sc) for sc in scales]
for i, acc in enumerate(accuracies):
ll, = plt.plot(range(len(acc)), acc, color=colors[i])
l.append(ll)
plt.ylabel('accuracy')
plt.legend(l, names, loc=2, prop={'size': 6})
if mode == 'train':
plt.xlabel('iterations')
else:
plt.xlabel('iterations x 1000')
path = os.path.join(self.path, 'accuracies_{}.png'.format(mode))
plt.savefig(path)
def plot_norm_points(self, Inputs_N, e, Perms, scales, fig=1):
input = Inputs_N[0][0].data.cpu().numpy()
e = torch.sort(e, 1)[0][0].data.cpu().numpy()
Perms = [perm[0].data.cpu().numpy() for perm in Perms]
plt.figure(fig)
plt.clf()
ee = e.copy()
for i, perm in enumerate(Perms):
plt.subplot(1, len(Perms), i + 1)
colors = cm.rainbow(np.linspace(0, 1, 2 ** (scales - i)))
perm = perm[np.where(perm > 0)[0]] - 1
points = input[perm]
e_scale = ee[perm]
for node in xrange(2 ** (scales - i)):
ind = np.where(e_scale == node)[0]
pts = points[ind]
plt.scatter(pts[:, 0], pts[:, 1], c=colors[node])
ee //= 2
path = os.path.join(self.path, 'visualize_example.png')
plt.savefig(path)
def contour_plot(self, sensors=[0.2,0.2,0.2,0.0], title="Contour Plot of Q(s,a)"):
#
# Show a contour plot of how Q varies over the geometry of our
# play area, while fixing sensor readings and car rotation.
#
x,y,z = self.location_contours(sensors)
plt.figure(facecolor='white')
plt.hot()
im = plt.imshow(z, interpolation='bilinear', origin='lower', cmap=cm.inferno)
CBI = plt.colorbar(im, orientation='horizontal', shrink=0.8)
plt.title(title+": theta="+str(int(sensors[3]*180.0/np.pi)))
plt.xlabel('x%')
plt.ylabel('y%')
plt.show()
def angle_v_sensor_plot(self, x0=0.5, y0=0.5, title="Contour Plot of Q(s,a)"):
#
# Show a contour plot of how Q varies as we change car rotation
# and sensor strength at a fixed position (x0,y0) in the game area.
#
x,y,z = self.angle_v_sensor_contours(x0, y0)
plt.figure(facecolor='white')
plt.hot()
plt.xlabel('Orientation')
plt.ylabel('Signal strength')
im = plt.imshow(z, interpolation='bilinear', origin='lower', cmap=cm.inferno)
CBI = plt.colorbar(im, orientation='horizontal', shrink=0.8)
plt.title(title)
plt.show()
def theta_anim(self):
#
# Animate the contour plot from above by varying theta from 0 to 2*pi
#
self.theta = 0
x,y,z = self.location_contours([0.2, 0.2, 0.2, self.theta])
self.fig = plt.figure()
self.im = plt.imshow(z, interpolation='bilinear', origin='lower', cmap=cm.inferno)
CBI = plt.colorbar(self.im, orientation='horizontal', shrink=0.8)
plt.title('Contour Plot - Q')
ani = animation.FuncAnimation(self.fig, self.update_theta, interval=50, blit=False)
plt.show()
def theta_gif(self):
#
# Create an animated gif of the contour plot from above by varying theta from 0 to pi
#
self.theta = 0
x,y,z = self.location_contours([0.2, 0.2, 0.2, self.theta])
self.fig = plt.figure()
self.im = plt.imshow(z, interpolation='bilinear', origin='lower', cmap=cm.inferno)
CBI = plt.colorbar(self.im, orientation='horizontal', shrink=0.8)
plt.xlabel('X %')
plt.ylabel('Y %')
ani = animation.FuncAnimation(self.fig, self.update_theta, frames=np.arange(0,20), interval=200, blit=False)
ani.save('figures/theta.gif', dpi=80, writer='imagemagick')
def sensor_anim(self, theta=0):
#
# Animate the contour plot by changing sensor values and holding
# the angle fixed at theta.
#
self.theta = theta
self.sensor = 0.0
x,y,z = self.location_contours([0,0,0, self.theta])
self.fig = plt.figure()
self.im = plt.imshow(z, interpolation='bilinear', origin='lower', cmap=cm.inferno)
CBI = plt.colorbar(self.im, orientation='horizontal', shrink=0.8)
ani = animation.FuncAnimation(self.fig, self.update_sensor, interval=50, blit=False)
plt.show()
def plotImage(self, I, ax=None, showIt=False, grid=False, clim=None):
if self.dim == 3: raise Exception('Use plot slice?')
import matplotlib.pyplot as plt
import matplotlib
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.colors as colors
import matplotlib.cm as cmx
if ax is None: ax = plt.subplot(111)
jet = cm = plt.get_cmap('jet')
cNorm = colors.Normalize(
vmin=I.min() if clim is None else clim[0],
vmax=I.max() if clim is None else clim[1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
ax.set_xlim((self.x0[0], self.h[0].sum()))
ax.set_ylim((self.x0[1], self.h[1].sum()))
for ii, node in enumerate(self._sortedCells):
x0, sz = self._cellN(node), self._cellH(node)
ax.add_patch(plt.Rectangle((x0[0], x0[1]), sz[0], sz[1], facecolor=scalarMap.to_rgba(I[ii]), edgecolor='k' if grid else 'none'))
# if text: ax.text(self.center[0],self.center[1],self.num)
scalarMap._A = [] # http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots
ax.set_xlabel('x')
ax.set_ylabel('y')
if showIt: plt.show()
return [scalarMap]
def plotImage(
self, I, ax=None, showIt=False, grid=False, clim=None
):
if self.dim == 3:
raise NotImplementedError('This is not yet done!')
import matplotlib.pyplot as plt
import matplotlib
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.colors as colors
import matplotlib.cm as cmx
if ax is None:
ax = plt.subplot(111)
jet = cm = plt.get_cmap('jet')
cNorm = colors.Normalize(
vmin=I.min() if clim is None else clim[0],
vmax=I.max() if clim is None else clim[1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
# ax.set_xlim((self.x0[0], self.h[0].sum()))
# ax.set_ylim((self.x0[1], self.h[1].sum()))
Nx = self.r(self.gridN[:, 0], 'N', 'N', 'M')
Ny = self.r(self.gridN[:, 1], 'N', 'N', 'M')
cell = self.r(I, 'CC', 'CC', 'M')
for ii in range(self.nCx):
for jj in range(self.nCy):
I = [ii, ii+1, ii+1, ii]
J = [jj, jj, jj+1, jj+1]
ax.add_patch(plt.Polygon(np.c_[Nx[I, J], Ny[I, J]], facecolor=scalarMap.to_rgba(cell[ii, jj]), edgecolor='k' if grid else 'none'))
scalarMap._A = [] # http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots
ax.set_xlabel('x')
ax.set_ylabel('y')
if showIt:
plt.show()
return [scalarMap]
def _cmap_to_rgb(mplmap, values):
from matplotlib import cm
cmap = getattr(cm, mplmap)
mx = values.max()
mn = values.min()
cat_values = (values-mn)/(mx-mn) # rescale values [0.0,1.0]
rgba = cmap(cat_values) # array of RGBA values in range [0.0, 1.0]
# strip alpha field and rescale to [0,255] RGB integers
rgb = [list(map(int, c[:3]*256.0)) for c in rgba]
return rgb
def _set_cmap(self):
import matplotlib.cm as cm
if hasattr(cm, "viridis"):
return "viridis"
else:
return "jet"
def _add_colorbar(ax, cmap, cmap_data, norm):
"""Show a colorbar right of the plot.
Parameters
----------
ax : plt.Axes
cmap : colors.Colormap
cmap_data : array_like
norm : colors.Normalize
"""
fig = ax.get_figure()
mappable = cm.ScalarMappable(cmap=cmap, norm=norm)
mappable.set_array(cmap_data) # TODO: Or what???
fig.colorbar(mappable, ax=ax)
def set_background_color(self, field, color=None):
"""set the background color to match provided color
Parameters
----------
field : string
the field to set the colormap
if field == 'all', applies to all plots.
color : string or RGBA tuple (optional)
if set, set the background color to this color
if unset, background color is set to the bottom value of
the color map
"""
actual_field = self.data_source._determine_fields(field)[0]
if color is None:
cmap = self._colormaps[actual_field]
if isinstance(cmap, string_types):
try:
cmap = yt_colormaps[cmap]
except KeyError:
cmap = getattr(matplotlib.cm, cmap)
color = cmap(0)
if LooseVersion(matplotlib.__version__) < LooseVersion("2.0.0"):
self.plots[actual_field].axes.set_axis_bgcolor(color)
else:
self.plots[actual_field].axes.set_facecolor(color)
return self
def _colorbar_index(ncolors, cmap):
cmap = _cmap_discretize(cmap, ncolors)
mappable = cm.ScalarMappable(cmap=cmap)
mappable.set_array([])
mappable.set_clim(-0.5, ncolors+0.5)
colorbar = plt.colorbar(mappable)
colorbar.set_ticks(np.linspace(0, ncolors, ncolors))
colorbar.set_ticklabels(range(ncolors))
def abs_diff_map_args(vmin=0, vmax=0.1):
return {"vmin": vmin,
"vmax": vmax,
"interpolation": "none",
"cmap": cm.YlOrRd}
def plot_samples(samples, dist, noise, modelno, num_samples, timestamp):
"""Plot the observed samples and posterior samples side-by-side."""
print 'Plotting samples %s %f' % (dist, noise)
fig, ax = plt.subplots(nrows=1, ncols=2)
fig.suptitle(
'%s (noise %1.2f, sample %d)' % (dist, noise, modelno),
size=16)
# Plot the observed samples.
T = simulate_dataset(dist, noise, num_samples)
# ax[0].set_title('Observed Data')
ax[0].text(
.5, .95, 'Observed Data',
horizontalalignment='center',
transform=ax[0].transAxes)
ax[0].set_xlabel('x1')
ax[0].set_ylabel('x2')
ax[0].scatter(T[:,0], T[:,1], color='k', alpha=.5)
ax[0].set_xlim(simulator_limits[dist][0])
ax[0].set_ylim(simulator_limits[dist][1])
ax[0].grid()
# Plot posterior distribution.
# ax[1].set_title('CrossCat Posterior Samples')
ax[1].text(
.5, .95, 'CrossCat Posterior Samples',
horizontalalignment='center',
transform=ax[1].transAxes)
ax[1].set_xlabel('x1')
clusters = set(samples[:,2])
colors = iter(matplotlib.cm.gist_rainbow(
np.linspace(0, 1, len(clusters)+2)))
for c in clusters:
sc = samples[samples[:,2] == c][:,[0,1]]
ax[1].scatter(sc[:,0], sc[:,1], alpha=.5, color=next(colors))
ax[1].set_xlim(ax[0].get_xlim())
ax[1].set_ylim(ax[0].get_ylim())
ax[1].grid()
# Save.
# fig.set_tight_layout(True)
fig.savefig(filename_samples_figure(dist, noise, modelno, timestamp))
plt.close('all')
def test_dna_assembly_example(tmpdir):
spreadsheet_path = os.path.join('examples', 'examples_data',
"dna_assembly.xls")
colors = (cm.Paired(0.21 * i % 1.0) for i in range(30))
resources = resources_from_spreadsheet(
spreadsheet_path=spreadsheet_path, sheetname="resources")
processes = [
tasks_from_spreadsheet(spreadsheet_path=spreadsheet_path,
sheetname="process",
resources_dict=resources,
tasks_color=next(colors),
task_name_prefix="WU%d_" % (i + 1))
for i in range(5)
]
print("NOW OPTIMIZING THE SCHEDULE, BE PATIENT...")
new_processes = schedule_processes_series(
processes, est_process_duration=5000, time_limit=6)
# PLOT THE TASKS DEPENDENCY TREE
ax = plot_tasks_dependency_graph(processes[0])
ax.set_title("PLAN OF A WORK UNIT")
ax.figure.savefig("basic_example_work_unit.pdf", bbox_inches="tight")
# PLOT THE OPTIMIZED SCHEDULE
ax = plot_schedule([t for process in new_processes for t in process])
ax.figure.set_size_inches((8, 5))
ax.set_xlabel("time (min)")
ax.figure.savefig(os.path.join(str(tmpdir),
"basic_example_schedule.png"),
bbox_inches="tight")
def get_scalar_map(x_min, x_max, color_map='jet'):
cm = plt.get_cmap(color_map)
cNorm = matplotlib.colors.Normalize(vmin=x_min, vmax=x_max)
return cmx.ScalarMappable(norm=cNorm, cmap=cm)
def __init__(self, name, z, x, y):
self.name = name
self.z = z
self.x = x
self.y = y
self.lDcm = cosmo.luminosity_distance(self.z)*u.Mpc.to(u.cm) / u.Mpc
self.radToKpc = conv.arcsec_per_kpc_proper(self.z)*0.05/u.arcsec*u.kpc
# We grab our galaxy data and make a list of galaxy objects
def set_lines_color_cycle_map(name, length):
cmap = getattr(plt.cm, name)
c = cycler('color', cmap(np.linspace(0, 1, length)))
matplotlib.rcParams['axes.prop_cycle'] = c
def imscatter(x, y, image, ax=None, color=None, days=None):
"""Scatter image at x, y on scatter graph
Args:
x (int): x location of data point
y (int): y location of data point
image: PIL image to be displayed
ax: scatterplot handle
color (r,g,b,a): if not None, border color
days (list of int): if not None, select color based on time of datapoint and days contains
the days present in dataset
Returns:
artists (list of axis artists)
"""
if ax is None:
ax = plt.gca()
try:
image = plt.imread(image)
except TypeError:
# Likely already an array...
pass
x, y = np.atleast_1d(x, y)
artists = []
cmap = matplotlib.cm.get_cmap('nipy_spectral')
for x0, y0, im0 in zip(x, y, image):
if days:
# Assumes around 700 videos per day
color = cmap((days.index(int(im0.split("/")[-1].split("_")[1]))*700+int(im0.split("/")[-1].split("_")[2]))/((len(days))*700.0))
if os.path.exists(im0):
im = load_img_seq(im0, resize_size=(1,1), color=color)
im = OffsetImage(im, zoom=2)
ab = AnnotationBbox(im, (x0, y0), xycoords='data', frameon=frameon)
artists.append(ax.add_artist(ab))
ax.update_datalim(np.column_stack([x, y]))
ax.autoscale()
return artists
def plot_graph(self, am, position=None, cls=None, fig_name='graph.png'):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
g = nx.from_numpy_matrix(am)
if position is None:
position=nx.drawing.circular_layout(g)
fig = plt.figure()
if cls is None:
cls='r'
else:
# Make a user-defined colormap.
cm1 = mcol.LinearSegmentedColormap.from_list("MyCmapName", ["r", "b"])
# Make a normalizer that will map the time values from
# [start_time,end_time+1] -> [0,1].
cnorm = mcol.Normalize(vmin=0, vmax=1)
# Turn these into an object that can be used to map time values to colors and
# can be passed to plt.colorbar().
cpick = cm.ScalarMappable(norm=cnorm, cmap=cm1)
cpick.set_array([])
cls = cpick.to_rgba(cls)
plt.colorbar(cpick, ax=fig.add_subplot(111))
nx.draw(g, pos=position, node_color=cls, ax=fig.add_subplot(111))
fig.savefig(os.path.join(self.plotdir, fig_name))
def set_style(font_scale=None):
# use default Latex font for math even with matplotlib 2.0
mpl.rcParams['mathtext.fontset'] = 'cm'
if font_scale is not None:
mpl.rcParams['font.size'] = 10 * font_scale
def plot_classes(self, points, clusters, e, fig=0):
e = e[0].data.cpu().numpy()
points = points[0]
plt.figure(fig)
plt.clf()
colors = cm.rainbow(np.linspace(0, 1, clusters))
for cl in range(clusters):
ind = np.where(e == cl)[0]
pts = points[ind]
plt.scatter(pts[:, 0], pts[:, 1], c=colors[cl])
plt.title('clustering')
path = os.path.join(self.path, 'clustering_ex.png'.format(clusters))
plt.savefig(path)
def plot_example(self, x, y, clusters, length):
plt.figure(0)
plt.clf()
colors = cm.rainbow(np.linspace(0, 1, clusters))
for c in range(clusters):
ind = np.where(y == c)[0]
plt.scatter(x[ind, 0], x[ind, 1], c=colors[c])
path = '/home/anowak/DynamicProgramming/DP/plots/example.png'
plt.savefig(path)