【发布时间】:2023-01-16 23:38:26
【问题描述】:
标签: python matplotlib plot plotly
标签: python matplotlib plot plotly
我不认为这是明确支持的。您可以通过向图例添加额外的虚假条目来解决它(在您的情况下为 3)。考虑:
import numpy as np
import matplotlib.pyplot as plt
plt.figure()
# Actual data
for i in range(13):
plt.plot(np.random.random(), np.random.random(), '.', label=chr(ord('A') + i))
# Fake data, for the legend
plt.plot(0, np.zeros([1, 3]), '.', ms=0, label=' ')
plt.legend(ncol=4)
plt.show() # or plt.savefig('figname.png')
在这里,我使用了 0 的标记大小 (ms),确保绘制的假数据点不会出现在绘图或图例上。
【讨论】:
您可以添加一些虚拟图例句柄来填充空白区域:
from matplotlib import pyplot as plt
labels = 'abcdefghijklm'
for i, (label) in enumerate(labels):
plt.bar([i], (i + 1) ** 2, color=plt.cm.turbo_r(i / len(labels)), label=label)
handles, labels = plt.gca().get_legend_handles_labels()
dummy_handle = plt.Rectangle((0, 0), 0, 0, color='none', label='')
plt.legend(handles=handles + 3*[dummy_handle], ncol=4)
plt.show()
【讨论】: