Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
heatmap
size: the size of the heatmap to be plotted, default is 16
"""
# Generate a mask for the upper triangle
mask = np.zeros_like(dataframe.corr(), dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Set up the matplotlib figure
_, _ = plt.subplots(figsize=(size, size))
# Generate a custom diverging colormap
cmap = sns.diverging_palette(220, 10, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(dataframe.corr(), mask=mask, cmap=cmap, vmax=1.0, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5})
table.add_row(FootnoteText('Length'), FootnoteText('{:,}'.format(len(trace_addresses))))
doc.append('\n')
im = np.zeros((addresses, len(trace_addresses)))
for i in range(len(trace_addresses)):
address = trace_addresses[i]
address_i = plt_addresses.index(address)
im[address_i, i] = 1
truncate = 100
for col_start in range(0, len(trace_addresses), truncate):
col_end = min(col_start + truncate, len(trace_addresses))
with doc.create(Figure(position='H')) as plot:
fig = plt.figure(figsize=(20 * ((col_end + 4 - col_start) / truncate),4))
ax = plt.subplot(111)
# ax.imshow(im,cmap=plt.get_cmap('Greys'))
sns.heatmap(im[:,col_start:col_end], cbar=False, linecolor='lightgray', linewidths=.5, cmap='Greys',yticklabels=plt_addresses,xticklabels=np.arange(col_start,col_end))
plt.yticks(rotation=0)
fig.tight_layout()
plot.add_plot(width=NoEscape(r'{0}\textwidth'.format((col_end + 4 - col_start) / truncate)), placement=NoEscape(r'\raggedright'))
with doc.create(Figure(position='H')) as plot:
pairs = {}
for left, right in zip(trace_addresses, trace_addresses[1:]):
if (left, right) in pairs:
pairs[(left, right)] += 1
else:
pairs[(left, right)] = 1
fig = plt.figure(figsize=(10,5))
ax = plt.subplot(111)
graph = pydotplus.graphviz.graph_from_dot_data(master_graph.to_string())
def attention_visualization(att):
sns.heatmap(att[0, :, :])
plt.show()
def plot_eigenoptions(self, folder, sess):
# feed_dict = {self.orig_net.matrix_sf: self.matrix_sf}
# s, v = sess.run([self.orig_net.s, self.orig_net.v], feed_dict=feed_dict)
u, s, v = np.linalg.svd(self.matrix_sf, full_matrices=False)
eigenvalues = s
eigenvectors = v
# U, s, V = np.linalg.svd(matrix)
S = np.diag(s[1:])
sr_r_m = np.dot(u[:, 1:], np.dot(S, v[1:]))
import seaborn as sns
sns.plt.clf()
ax = sns.heatmap(sr_r_m, cmap="Blues")
ax.set(xlabel='SR_vect_size=128', ylabel='Grid states/positions')
folder_path = os.path.join(os.path.join(self.config.stage_logdir, "summaries"), "eigenoptions")
tf.gfile.MakeDirs(folder_path)
sns.plt.savefig(os.path.join(folder_path, 'reconstructed_sr.png'))
sns.plt.close()
folder_path = os.path.join(os.path.join(self.config.stage_logdir, "summaries"), folder)
tf.gfile.MakeDirs(folder_path)
# variance_eigenvectors = []
# for i in range(self.nb_states):
# variance_eigenvectors.append([])
# for i in range(self.nb_states):
# variance_eigenvectors[i].append(np.var(eigenvectors[:, i]))
# sns.plt.clf()
# sns.plt.plot(variance_eigenvectors[i])
# xx = np.arange(0, len(x), 1)
# yy = np.arange(0, len(y), 1)
# extent2 = np.min(xx), np.max(xx), np.min(yy), np.max(yy)
fig2, bx = plt.subplots(1, 1) # figsize = figureTableDims
bx.cla()
sns.set(font_scale = fontScale)
if args.trans:
table = np.transpose(table)
x, y = y, x
tableMap = pandas.DataFrame(data = table, index = x, columns = y)
bx = sns.heatmap(tableMap, cmap = "Purples", cbar = False, linewidths = .5, linecolor = "gray", square = True)
# x ticks
if args.trans:
bx.xaxis.tick_top()
locs, labels = plt.xticks()
if args.trans:
plt.setp(labels, rotation = 0)
else:
plt.setp(labels, rotation = 60)
# y ticks
locs, labels = plt.yticks()
plt.setp(labels, rotation = 0)
plt.savefig(outTableAttName(instance, name), dpi = 720)
def _plot_heatmap(call_csv, samples, positions, sample_info, batch_counts):
def sample_sort(x):
batch = sample_info[x]["batch"]
return (-batch_counts.get(batch, 0), batch, x)
out_file = "%s.png" % os.path.splitext(call_csv)[0]
df = pd.read_csv(call_csv)
sv_rect = df.pivot(index="position", columns="sample", values="caller_support")
sv_rect = sv_rect.reindex_axis(positions, axis=0)
sv_rect = sv_rect.reindex_axis(["%s: %s" % (sample_info[x]["batch"], x)
for x in sorted(samples, key=sample_sort)],
axis=1)
fig = plt.figure(tight_layout=True)
plt.title("Shared structural variant calls for affected and unaffected in regions of interest",
fontsize=16)
ax = sns.heatmap(sv_rect, cbar=False,
cmap=sns.diverging_palette(255, 1, n=3, as_cmap=True))
colors = sns.diverging_palette(255, 1, n=3)
b1 = plt.bar(0, 0, bottom=-100, color=colors[-1])
b2 = plt.bar(0, 0, bottom=-100, color=colors[0])
ax.legend([b1, b2], ["affected", "unaffected"], ncol=2,
bbox_to_anchor=(0.85, 0.995), loc=3)
plt.setp(ax.get_xticklabels(), fontsize=8)
plt.setp(ax.get_yticklabels(), fontsize=8)
fig.set_size_inches(20, 8)
fig.savefig(out_file)
def drawHeatmap(df, color, output, labelsize, annotate):
with warnings.catch_warnings():
warnings.simplefilter('ignore')
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
#get size of table
width = len(df.columns) / 2
height = len(df.index) / 4
fig, ax = plt.subplots(figsize=(width,height))
cbar_ax = fig.add_axes(shrink=0.4)
if annotate:
sns.heatmap(df,linewidths=0.5, cmap=color, ax=ax, fmt="d", annot_kws={"size": 4}, annot=True)
else:
sns.heatmap(df,linewidths=0.5, cmap=color, ax=ax, annot=False)
plt.yticks(rotation=0)
plt.xticks(rotation=90)
for item in ax.get_xticklabels():
item.set_fontsize(8)
for item in ax.get_yticklabels():
item.set_fontsize(int(labelsize))
fig.savefig(output, format='pdf', dpi=1000, bbox_inches='tight')
plt.close(fig)
def _indicator_plot(data,
sample_col,
indicator_col,
colormap=None,
figsize=None,
ax=None):
indicator_data = data.set_index([sample_col])[[indicator_col]].T
indicator_plot = sb.heatmap(indicator_data,
square=True,
cbar=None,
xticklabels=True,
linewidths=1,
cmap=colormap,
ax=ax)
plt.setp(indicator_plot.axes.get_yticklabels(), rotation=0)
return indicator_plot
pal2 = sns.blend_palette(["#f7f7f7", "#fddbc7", "#f4a582", "#d6604d", "#b2182b", "#67001f"], as_cmap=True)
sns.heatmap(cm.transpose(),
fmt=fmt,
annot=True,
cmap=pal1,
linewidths=0,
cbar=False,
mask=mask1,
ax=ax,
xticklabels=labels,
yticklabels=labels,
square=True,
annot_kws={'size': 'small'})
sns.heatmap(cm.transpose(),
fmt=fmt,
annot=True,
cmap=pal2,
linewidths=0,
cbar=False,
mask=mask2,
ax=ax,
xticklabels=labels,
yticklabels=labels,
square=True,
annot_kws={'size': 'small'})
for _, spine in ax.spines.items():
spine.set_visible(True)
ax.set_xlabel('Input')
ax.set_ylabel('Predicted')
cluster_i_temp_sort = np.sort(cluster_i_temp, order=years)
cluster_i_temp_sort = np.array(list(map(list, cluster_i_temp_sort)))
if not cluster_i_temp_sort.shape[0]:
ax.set_axis_off()
continue
elif cluster_i_temp_sort.shape[0] < max_cluster:
diff_n = max_cluster - cluster_i_temp_sort.shape[0]
bigger = np.unique(cluster_i_temp_sort).max()+1
cluster_i_temp_sort = np.append(cluster_i_temp_sort, np.zeros(
(diff_n, cluster_i_temp_sort.shape[1]))+bigger, axis=0)
df_cluster_i_temp_sort = pd.DataFrame(cluster_i_temp_sort,
columns=years)
if cluster_i_temp.shape[0] == max_cluster:
cbar_ax = fig.add_axes([0.3, -0.02, 0.42, 0.02])
ax = sns.heatmap(df_cluster_i_temp_sort, ax=ax, cmap=cluster_cmap,
cbar_kws={"orientation": "horizontal"},
cbar_ax=cbar_ax)
colorbar = ax.collections[0].colorbar
colorbar.set_ticks(np.linspace(min(neighborhood) + 0.5, max(neighborhood) - 0.5, k))
colorbar.set_ticklabels(neighborhood)
else:
ax = sns.heatmap(df_cluster_i_temp_sort, ax=ax, cmap=my_cmap,
cbar=False)
plt.tight_layout()
# fig.tight_layout(rect=[0, 0, .9, 1])
if save_fig:
dirName = "figures"
if not path.exists(dirName):
mkdir(dirName)