[英]Add colorbar as legend to matplotlib scatterplot (multiple subplots, multiple scatters)
[英]How to add legend labels per plotted column to multiple scatterplot subplots?
我使用以下代碼創建了多個散點圖子圖:
# Value counts of the samples in each cluster
counts = clustered_series.value_counts()
fig, axs = plt.subplots(2, 4, figsize = (35.7, 16))
for clust, ax in zip(np.unique(clusters), axs.flat):
tickers = list(clustered_series[clustered_series==clust].index)
means = sample.loc[tickers][tickers].mean()
data = sample.loc[tickers][tickers].sub(means)
pairs = list(itertools.combinations(data.columns, 2))
for pair in pairs:
sns.scatterplot(data = data, x = pair[0], y = pair[1], ax = ax)
ax.set_title(label='Stock Alphas Correlation for Cluster %d' % clust)
plt.suptitle("Stocks' Alphas Clusters by Correlation", fontsize = 14, weight = 'bold')
fig.tight_layout()
這counts
:
2 13
7 11
3 10
5 8
1 7
6 6
4 5
dtype: int64
這是我的散點圖:
我正在做的是 plot 每個集群中每個可能的列和行對在每個子圖中相互對。 我每個集群都有一個子表。 這是第 7 組的表格:
我想通過顏色來區分每個點,這些點屬於哪個股票(列或行),並在每個子圖的圖例中顯示。 例如,如果我在集群 1 中有 8 對股票,我想在圖例中顯示唯一的股票名稱,並且 plot 中的點應該在 8 對中每個唯一股票都有一個顏色。 我嘗試了sns.scatterplot
的hue
參數,但它為每個 plot 創建了一個巨大的圖例,其中為每個點分配了顏色,這不是我想要的。
我怎樣才能做到這一點?
提前致謝。
通過將調用從plt.scatter
更改為ax.scatter
並將每對中唯一特征名稱的列表傳遞給ax.legend
調用來解決它,如下所示:
# Value counts of the samples in each cluster
counts = clustered_series.value_counts()
fig, axs = plt.subplots(2, 4, figsize = (35.7, 16))
for clust, ax in zip(np.unique(clusters), axs.flat):
tickers = list(clustered_series[clustered_series==clust].index)
means = sample.loc[tickers][tickers].mean()
data = sample.loc[tickers][tickers].sub(means)
#data['clusters'] = clusters[clusters == clust]
pairs = list(combinations(data.columns, 2))
for pair in pairs:
ax.scatter(x = data[pair[0]], y = data[pair[1]], cmap = 'Dark2')
ax.set_title(label='Stock Alphas Correlation for Cluster %d' % clust)
ax.legend(np.unique(np.concatenate(pairs)).tolist())
plt.suptitle("Stocks' Alphas Clusters by Correlation", fontsize = 14, weight = 'bold')
fig.tight_layout()
這是我現在得到的結果,這正是我想要的:
希望這會幫助某人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.