开发者社区> 问答> 正文

如何修改散点图图例以显示相同类型手柄的不同格式?

我正在尝试修改包含两个重叠散点图的图形的图例。更具体地说,我需要两个图例手柄和标签:第一个手柄将包含多个点(每个都具有不同的颜色),而另一个手柄则由一个点组成。

根据这个相关问题,我可以修改图例手柄以显示多个点,每个点都有不同的颜色。

根据这个类似的问题,我知道可以更改指定句柄显示的点数。但是,这会将更改应用于图例中的所有句柄。只能将其应用于一个手柄吗?

我的目标是将两种方法结合起来。有没有办法做到这一点?

如果不清楚,我想修改嵌入的图形(如下所示),以使Z vs X句柄在相应的图例标签旁边仅显示一个点,而保留Y vs X句柄不变。

我未能产生这样一个数字的尝试如下:

要复制此图,可以运行以下代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple, HandlerRegularPolyCollection

class ScatterHandler(HandlerRegularPolyCollection):

    def update_prop(self, legend_handle, orig_handle, legend):
        """ """
        legend._set_artist_props(legend_handle)
        legend_handle.set_clip_box(None)
        legend_handle.set_clip_path(None)

    def create_collection(self, orig_handle, sizes, offsets, transOffset):
        """ """
        p = type(orig_handle)([orig_handle.get_paths()[0]], sizes=sizes, offsets=offsets, transOffset=transOffset, cmap=orig_handle.get_cmap(), norm=orig_handle.norm)
        a = orig_handle.get_array()
        if type(a) != type(None):
            p.set_array(np.linspace(a.min(), a.max(), len(offsets)))
        else:
            self._update_prop(p, orig_handle)
        return p

x = np.arange(10)
y = np.sin(x)
z = np.cos(x)

fig, ax = plt.subplots()
hy = ax.scatter(x, y, cmap='plasma', c=y, label='Y vs X')
hz = ax.scatter(x, z, color='k', label='Z vs X')
ax.grid(color='k', linestyle=':', alpha=0.3)
fig.subplots_adjust(bottom=0.2)
handler_map = {type(hz) : ScatterHandler()}
fig.legend(mode='expand', ncol=2, loc='lower center', handler_map=handler_map, scatterpoints=5)

plt.show()
plt.close(fig)

我不喜欢的一种解决方案是创建两个图例-一个用于“ Z vs X”,另一个用于“ Y vs X”。但是,我的实际用例涉及可选数量的句柄(可以超过两个),并且我希望不必计算每个图例框的最佳宽度/高度。还有什么可以解决这个问题的呢?

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 22:24:09 516 0
1 条回答
写回答
取消 提交回答
  • 这是一个肮脏的把戏,不是一个很好的解决方案,但是您可以将ZX图例的其他点的大小设置为0。只需将最后两行更改为以下内容。

    leg = fig.legend(mode='expand', ncol=2, loc='lower center', handler_map=handler_map, scatterpoints=5)
    # The third dot of the second legend stays the same size, others are set to 0
    leg.legendHandles[1].set_sizes([0,0,leg.legendHandles[1].get_sizes()[2],0,0])
    

    结果如图所示。

    回答来源:stackoverflow

    2020-03-24 22:24:16
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载