python-3.x - 如何修改散点图图例以显示相同类型句柄的不同格式?
问题描述
我正在尝试修改包含两个叠加散点图的图例。更具体地说,我想要两个图例句柄和标签:第一个句柄将包含多个点(每个点的颜色不同),而另一个句柄由一个点组成。
根据这个相关问题,我可以修改图例句柄以显示多个点,每个点都是不同的颜色。
根据这个类似的问题,我知道我可以更改指定句柄显示的点数。但是,这会将更改应用于图例中的所有句柄。可以只用在一个手柄上吗?
我的目标是结合这两种方法。有没有办法做到这一点?
如果不清楚,我想修改嵌入图(见下文),使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
. 但是,我的实际用例涉及可选数量的句柄(可以超过两个),我不想计算每个图例框的最佳宽度/高度。还有什么办法可以解决这个问题?
解决方案
这是一个肮脏的技巧,而不是一个优雅的解决方案,但您可以将 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])
结果如图所示。
推荐阅读
- google-apps-script - 如何在 Google 表格顶部添加空白行
- hibernate - 我正在为我的项目使用 JPA 和休眠。有时效果很好。有时会出现内部服务器错误
- c# - 如何用内存中的引用替换引用?
- c - 带省略号的函数定义
- python - 无法确定将对象转换为日期时间的正确格式
- java - Gson在反序列化后添加“root”、“entrySet”、“values”字段
- c# - 如何在 Entity Framework / Linq 中按串联值排序?
- amazon-web-services - 遍历 PSOObject
- node.js - NodeJS集群背后的算法是什么?
- amazon-web-services - 可以使用角色使用 AWS SAM 进行本地开发吗?