一旦我想在网格图中绘制线条和误差条的复杂组合,我就会尝试在图例中完美地指示符号。我注意到,当任何符号类型是错误栏时,为它们应用所需的不透明度并不容易。
我尝试检查此post但未成功。
import matplotlib.pyplot as plt
from matplotlib.collections import PathCollection
from matplotlib.legend_handler import HandlerPathCollection, HandlerLine2D, HandlerErrorbar
x1 = np.linspace(0,1,8)
y1 = np.random.rand(8)
# Compute prediction intervals
sum_of_squares_mid = np.sum((x1 - y1) ** 2)
std_mid = np.sqrt(1 / (len(x1) - 2) * sum_of_squares_mid)
# Plot the prediction intervals
y_err_mid = np.vstack([std_mid, std_mid]) * 1.96
plt.plot(x1, y1, 'bo', label='label', marker=r"$\clubsuit$", alpha=0.2) # Default alpha is 1.0.
plt.errorbar(x1, y1, yerr=y_err_mid, fmt="o", ecolor="#FF0009", capsize=3, color="#FF0009", label="Errorbar", alpha=.1) # Default alpha is 1.0.
def update(handle, orig):
handle.update_from(orig)
handle.set_alpha(1)
plt.legend(handler_map={PathCollection : HandlerPathCollection(update_func = update),
plt.Line2D : HandlerLine2D( update_func = update),
plt.errorbar : HandlerErrorbar( update_func = update) # I added this but it deos not apply alpha=1 only for errobar symbol in legend
})
plt.show()
我目前的输出:
看来您没有为第二个
Artist
(即 ErrorbarContainer
)指定正确的处理程序,因此未针对该对象执行 set_alpha(1)
指令。
确实导入
import matplotlib.pyplot as plt
from matplotlib.container import ErrorbarContainer
from matplotlib.legend_handler import HandlerLine2D, HandlerErrorbar
然后将
handler_map
修改为
def update(handle, orig):
handle.update_from(orig)
handle.set_alpha(1)
leg = plt.legend(handler_map={
plt.Line2D : HandlerLine2D(update_func = update),
ErrorbarContainer: HandlerErrorbar(update_func = update)
})
结果
希望这有帮助!