使用matplotlib使用多种颜色的颜色轴脊柱
答
可以使用LineCollection
创建multicolored line。然后,您可以使用xaxis转换将其固定到x轴,而不受y限制的限制。将实际脊柱设置为不可见并关闭clip_on
使LineCollection看起来像轴脊柱。
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import numpy as np
fig, ax = plt.subplots()
colors=["b","r","lightgreen","gold"]
x=[0,.25,.5,.75,1]
y=[0,0,0,0,0]
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments,colors=colors, linewidth=2,
transform=ax.get_xaxis_transform(), clip_on=False)
ax.add_collection(lc)
ax.spines["bottom"].set_visible(False)
ax.set_xticks(x)
plt.show()
真棒。你能描述一下'transform = ax.get_xaxis_transform()'是做什么的?我似乎无法找到'transform'属性定义。 – JeeYem
您可能需要阅读[转换教程](http://matplotlib.org/users/transforms_tutorial.html)。每个艺术家都有变形属性。变换将坐标映射到画布。通常情况下,你不会太在意,因为你想使用数据坐标,而艺术家默认使用transData变换。在这种情况下,我们不希望根据数据坐标在y方向上确定线的位置,而是将其固定在坐标轴上。 'ax.get_xaxis_transform()'给出了一个转换,它需要数据单位中的x坐标和轴单位中的y坐标。 – ImportanceOfBeingErnest