有沒有辦法為 Matplotlib 中的單個圖例條目繪制多色線?
例如,在下圖中,條目 1 和 2 的線在中間點的左側顯示為黑色,在右側顯示為灰色。

uj5u.com熱心網友回復:
您可以通過元組圖例處理程式 ( 
PS:如果您有兩個子圖,則可以將兩者的句柄和標簽結合起來:
from matplotlib import pyplot as plt
from matplotlib.legend_handler import HandlerTuple
import numpy as np
fig, ax1 = plt.subplots()
ax1.plot(np.random.rand(2), color='black', ls='--', label='Class 1')
ax1.plot(np.random.rand(2), color='black', ls='-', label='Class 2')
ax2 = ax1.twinx()
ax2.plot(np.random.rand(2), color='.7', ls='--', label='Class 1')
ax2.plot(np.random.rand(2), color='.7', ls='-', label='Class 2')
handles1, labels1 = ax1.get_legend_handles_labels()
handles2, labels2 = ax2.get_legend_handles_labels()
labels = labels1 labels2
unique_labels = list(np.unique(labels))
combined_handles = [tuple([h for h, l in zip(handles1 handles2, labels) if l == label]) for label in unique_labels]
ax1.legend(handles=combined_handles, labels=unique_labels, handlelength=3,
handler_map={tuple: HandlerTuple(ndivide=None, pad=0)})
plt.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/478266.html
標籤:matplotlib
上一篇:Centos7部署Redis集群
下一篇:在Python中繪制圖形
