2017-05-30 122 views

回答

0

可以使用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() 

enter image description here

+0

真棒。你能描述一下'transform = ax.get_xaxis_transform()'是做什麼的?我似乎無法找到'transform'屬性定義。 – JeeYem

+0

您可能需要閱讀[轉換教程](http://matplotlib.org/users/transforms_tutorial.html)。每個藝術家都有變形屬性。變換將座標映射到畫布。通常情況下,你不會太在意,因爲你想使用數據座標,而藝術家默認使用transData變換。在這種情況下,我們不希望根據數據座標在y方向上確定線的位置,而是將其固定在座標軸上。 'ax.get_xaxis_transform()'給出了一個轉換,它需要數據單位中的x座標和軸單位中的y座標。 – ImportanceOfBeingErnest