我正在尝试为多个条目绘制多个间隔。
我尝试使用循环枚举条目,一次绘制一个间隔。
import matplotlib.pyplot as plt
intervals = [(1, 2), (1.1, 2.5), (1.2, 4), (1.5, 10), (1.7, 12)]
num_intervals = len(intervals)
viridis = plt.cm.get_cmap('viridis', num_intervals)
fig, ax = plt.subplots()
for idx, (min_int, max_int) in enumerate(intervals):
ax.hlines(y=idx, xmin=min_int, xmax=max_int, colors=viridis(idx / num_intervals), label=idx)
ax.legend()
plt.yticks([], [])
plt.show()
我希望使用matplotlib的内置方法一次绘制多个间隔。另外,我希望绘制图像中每个间隔的最小值和最大值。
答案 0 :(得分:2)
您可以调整代码以使用this答案中概述了其思想的LineCollection
。此外,您可以使用this方法将图例添加到LineCollection。
我修改了第一个答案,以使用列表理解功能以所需的格式创建lines
输入数据。
from matplotlib.lines import Line2D # Imported for legends
num_intervals = len(intervals)
viridis = plt.cm.get_cmap('viridis', num_intervals)
colors = np.array([viridis(idx / num_intervals) for idx in range(len(intervals))])
# Prepare the input data in correct format for LineCollection
lines = [[(i[0], j), (i[1], j)] for i, j in zip(intervals, range(len(intervals)))]
lc = mc.LineCollection(lines, colors= colors, linewidths=2)
fig, ax = pl.subplots()
ax.add_collection(lc)
ax.margins(0.1)
plt.yticks([], [])
# Adding the legends
def make_proxy(col, scalar_mappable, **kwargs):
color = col
return Line2D([0, 1], [0, 1], color=color, **kwargs)
proxies = [make_proxy(c, lc, linewidth=2) for c in colors]
ax.legend(proxies, range(5))
# Adding annotations
for i, x in enumerate(intervals):
plt.text(x[0], i+0.1, x[0], color=colors[i])
plt.text(x[1], i+0.1, x[1], color=colors[i])