如何在图例描述中引用其他容器?
How to reference other containers in legend description?
我想在元素的标签中引用另一个容器。我在下面附加了一些代码,而不是说“<5 位艺术家的 BarContainer 对象>”,我更希望有一个代表“数据”的蓝色框。
import numpy as np
from matplotlib import pyplot as plt
data = np.arange(5)
fig, ax = plt.subplots()
bar_1 = ax.bar(np.arange(len(data)), data, align="center", label="data")
ax.hlines(data.mean(), 0, len(data), ls="--", label=f"mean of {bar_1}")
plt.legend()
plt.show()
编辑:
我希望结果看起来像这样:
这是一个愚蠢的方法:
import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import numpy as np
from matplotlib import pyplot as plt
data = np.arange(5)
plt.close()
fig, ax = plt.subplots()
bar_1 = ax.bar(np.arange(len(data)), data, align="center", label="data")
ax.hlines(data.mean(), 0, len(data), ls="--", label=f"mean of {bar_1}")
ax1 = fig.add_subplot(221)
ax1.set_xlim(0, 1)
ax1.set_ylim(0, 1)
ax1.axis('off')
blue_patch = mpatches.Patch(label='data')
blue_dline = mlines.Line2D([], [], marker='', linestyle='--', label='mean of ')
nothing = mlines.Line2D([], [], marker='', linestyle='', label='')
ax2 = ax1.twinx()
ax2.axis('off')
ax1.legend(handles=[blue_dline, blue_patch], loc=(0.02, 0.7))
ax2.legend(handles=[blue_patch, nothing], framealpha=0, loc=(0.465, 0.7), handletextpad=0.2)
plt.show()
输出:
只要能用,谁在乎它是不是笨;)
我想在元素的标签中引用另一个容器。我在下面附加了一些代码,而不是说“<5 位艺术家的 BarContainer 对象>”,我更希望有一个代表“数据”的蓝色框。
import numpy as np
from matplotlib import pyplot as plt
data = np.arange(5)
fig, ax = plt.subplots()
bar_1 = ax.bar(np.arange(len(data)), data, align="center", label="data")
ax.hlines(data.mean(), 0, len(data), ls="--", label=f"mean of {bar_1}")
plt.legend()
plt.show()
编辑:
我希望结果看起来像这样:
这是一个愚蠢的方法:
import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import numpy as np
from matplotlib import pyplot as plt
data = np.arange(5)
plt.close()
fig, ax = plt.subplots()
bar_1 = ax.bar(np.arange(len(data)), data, align="center", label="data")
ax.hlines(data.mean(), 0, len(data), ls="--", label=f"mean of {bar_1}")
ax1 = fig.add_subplot(221)
ax1.set_xlim(0, 1)
ax1.set_ylim(0, 1)
ax1.axis('off')
blue_patch = mpatches.Patch(label='data')
blue_dline = mlines.Line2D([], [], marker='', linestyle='--', label='mean of ')
nothing = mlines.Line2D([], [], marker='', linestyle='', label='')
ax2 = ax1.twinx()
ax2.axis('off')
ax1.legend(handles=[blue_dline, blue_patch], loc=(0.02, 0.7))
ax2.legend(handles=[blue_patch, nothing], framealpha=0, loc=(0.465, 0.7), handletextpad=0.2)
plt.show()
输出:
只要能用,谁在乎它是不是笨;)