【问题标题】:How to add legend labels per plotted column to multiple scatterplot subplots?如何将每个绘制列的图例标签添加到多个散点图子图中?
【发布时间】:2021-07-19 14:35:05
【问题描述】:

我用这段代码创建了多个散点图子图:

# 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

这是我的散点图:

我正在做的是在每个子图中绘制每个集群中每一对可能的列和行。我每个集群都有一个子表。这是第 7 组的表格:

我想通过颜色来区分每个点,这些点属于哪个股票(列或行),并在每个子图的图例中显示。例如,如果我在集群 1 中有 8 对股票,我想在图例中显示唯一的股票名称,并且图中的点应该在 8 对中的每个唯一股票都有一个颜色。我已经尝试了sns.scatterplothue 参数,但它为每个图创建了一个巨大的图例,其中为每个点分配了一种颜色,这不是我想要的。

我该怎么做?

提前致谢。

【问题讨论】:

    标签: python python-3.x pandas matplotlib seaborn


    【解决方案1】:

    通过将调用从 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()
    

    这是我现在得到的结果,这正是我想要的:

    希望这会对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-03-22
      • 1970-01-01
      • 2020-03-30
      • 2019-09-16
      • 1970-01-01
      • 2017-08-21
      • 2018-11-12
      • 2019-05-08
      • 2017-11-10
      相关资源
      最近更新 更多