我有以下代码:
from string import letters
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white")
# Compute the correlation matrix
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
corr = df.corr()
# Generate a mask for the upper triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
# 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(corr, mask=mask, cmap=cmap, vmax=.3,
square=True, #xticklabels=5, #yticklabels=5,
linewidths=.5, cbar_kws={"shrink": .5}, ax=ax)
plt.show()
如何在图表右侧放置一个额外的图例,如下所示:
A: This is my first label
B: ...
C: ...
D: ...
我还希望为相关栏设置一个标签,简单地说是“相关”'。数据当然不是真实的数据。
答案 0 :(得分:1)
关于你的第一个问题,这是我设法做的事情:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
sns.set(style="white")
cols = list('ABCD')
# Compute the correlation matrix
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=cols)
corr = df.corr()
# Generate a mask for the upper triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
# 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(corr, mask=mask, cmap=cmap, vmax=.3,
square=True, #xticklabels=5, #yticklabels=5,
linewidths=.5, cbar_kws={"shrink": .5}, ax=ax)
pseudo_lines = []
strs = ['first', 'second', 'third', 'fourth']
for c, s in zip(cols, strs):
line = mlines.Line2D([], [], color='blue',
marker=r"${}:.This.is.my.{}.label$".format(c, s),
markersize=170, linestyle = 'None')
pseudo_lines.append(line)
plt.legend(handles=pseudo_lines, labelspacing=2)
plt.show()