我正在尝试设置一系列垂直轴跨度来象征不同时间的不同切换位置。例如,在下图中,切换位置 1(绿色)发生了很多次,在其他位置之间交替。
我在元组列表中绘制运行 for 循环的这些跨度,每个包含每个间隔的初始和最终索引以绘制 axvspan。
def plotShades(timestamp, intervals, colour):
for i in range(len(intervals)):
md.plt.axvspan(timestamp[intervals[i][0]], timestamp[intervals[i][1]], alpha=0.5, color=colour, label="interval")
然后调用另一个函数,绘制每个不同开关位置的阴影:
def plotAllOutcomes(timestamp, switches):
#switches is a list of 7 arrays indicating when the switcher is at each one of the 7 positions. If the array has a 1 value, the switcher is there. 0 otherwise.
colors = ['#d73027', '#fc8d59', '#fee08b', '#ffffbf', '#d9ef8b', '#91cf60', '#1a9850']
intervals = []
for i in range(len(switches)):
intervals.append(getIntervals(switches[i], timestamp))
plotShades(timestamp, intervals[i], colors[i])
md.plt.legend()
使用我放在这里的代码片段(不是最好的代码,我知道 - 我在 Python 中相当新!)图例最终每个间隔都有一个项目,这非常糟糕。这是它的外观:
我想得到一个只有 7 个项目的图例,每个项目都用于我的 axvspans 图中的一种颜色。我怎样才能继续这样做?我已经进行了相当广泛的搜索,但没有设法找到之前询问过的这种情况。预先感谢您的任何帮助!!
最佳答案
您可以使用标签以 "_"
开头的事实来应用一个小技巧。被忽略:
plt.axvspan( ... , label = "_"*i + "interval")
因此,仅针对
i==0
的情况创建标签。 .
关于python-3.x - 将多个 axvspan 标签设置为图例中的一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44632903/