当标记设置为像素时如何更改图例中的标记 size/scale

How to change marker size/scale in legend when marker is set to pixel

我正在用一个非常小的标记散点图数据点(见下面的屏幕截图)。当我使用非常小的标记 ',' 时,图例很难阅读(示例代码取自 here)。
(Python3、Jupyter实验室)

如何增加图例中标记的大小。上述网站上显示的两个版本均无效:

legend = ax.legend(frameon=True)  
for legend_handle in legend.legendHandles:  
    legend_handle._legmarker.set_markersize(9)

ax.legend(markerscale=6)

这两个解决方案 但是当标记设置为 '.' 时有效。
怎样才能在图例中展示更大的庄家?

来自 intoli.com 的示例代码:

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(12)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

for i in range(5):
    mean = [np.random.random()*10, np.random.random()*10]
    covariance = [ [1 + np.random.random(), np.random.random() - 1],  [0, 1 + np.random.random()], ]
    covariance[1][0] = covariance[0][1]  # must be symmetric
    x, y = np.random.multivariate_normal(mean, covariance, 3000).T
    plt.plot(x, y, ',', label=f'Cluster {i + 1}')

ax.legend(markerscale=12)

fig.tight_layout()
plt.show()

根据this discussion, the markersize has no effect when using pixels (,) as marker. How about generating a custom legend instead? For example, by adapting the first example in this tutorial,可以得到一个相当不错的传说:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

np.random.seed(12)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

for i in range(5):
    mean = [np.random.random()*10, np.random.random()*10]
    covariance = [ [1 + np.random.random(), np.random.random() - 1],  [0, 1 + np.random.random()], ]
    covariance[1][0] = covariance[0][1]  # must be symmetric
    x, y = np.random.multivariate_normal(mean, covariance, 3000).T
    plt.plot(x, y, ',', label=f'Cluster {i + 1}')



##generating custom legend
handles, labels = ax.get_legend_handles_labels()
patches = []
for handle, label in zip(handles, labels):
    patches.append(mpatches.Patch(color=handle.get_color(), label=label))

legend = ax.legend(handles=patches)

fig.tight_layout()
plt.show()

输出将如下所示:

通过将标记大小设置为 1 像素,您可以获得 plot 的 1 像素大小的标记。这看起来像

plt.plot(x, y, marker='s', markersize=72./fig.dpi, mec="None", ls="None")

上面所做的是将标记设置为正方形,将标记大小设置为 ppi(每英寸点数)除以 dpi(每英寸点数)== 点数 == 像素,并删除线条和边缘。

那么您尝试使用图例中的 markerscale 的解决方案效果很好。

完整示例:

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(12)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

for i in range(5):
    mean = [np.random.random()*10, np.random.random()*10]
    covariance = [ [1 + np.random.random(), np.random.random() - 1],  [0, 1 + np.random.random()], ]
    covariance[1][0] = covariance[0][1]  # must be symmetric
    x, y = np.random.multivariate_normal(mean, covariance, 3000).T
    plt.plot(x, y, marker='s', markersize=72./fig.dpi, mec="None", ls="None", 
             label=f'Cluster {i + 1}')

ax.legend(markerscale=12)

fig.tight_layout()
plt.show()