如何在matplotlib中从下到上垂直制作渐变颜色

时间:2019-03-25 16:58:48

标签: python matplotlib

我已成功将具有渐变颜色的numpy数据显示给matplotlib,但是在matplotlib中,颜色渐变水平显示,如何使渐变垂直可见?

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
c = np.arange(1,200)
x = np.arange(1,200)
y = np.random.randint(low=1, high=100, size=200)

cm = plt.get_cmap('jet')

fig = plt.figure(figsize=(10,5))
ax1 = plt.subplot(111)

no_points = len(c)
ax1.set_color_cycle([cm(1.*i/(no_points-1)) for i in range(no_points-1)])

for i in range(no_points-1):
    bar = ax1.plot(x[i:i+2],y[i:i+2])
plt.show()

结果如下:

result

相反,我想要一个垂直的颜色渐变。

1 个答案:

答案 0 :(得分:1)

我稍稍更改了您的代码,但主要只是将其与注释者所引用的the matplotlib recipe合并。这对我有用:

import numpy as np
import matplotlib.pyplot as plt

x_ = np.linspace(1, 200, 200)
y_ = np.random.randint(low=1, high=100, size=200)

# You need to interpolate because your line segments are short.
x = np.linspace(1, 200, 4000)
y = np.interp(x, x_, y_)

# Now follow the maplotlib recipe.
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)

fig, ax = plt.subplots(figsize=(15, 5))

norm = plt.Normalize(y.min(), y.max())
lc = LineCollection(segments, cmap='viridis', norm=norm)

lc.set_array(y)
lc.set_linewidth(2)
line = ax.add_collection(lc)
plt.colorbar(line, ax=ax)

ax.set_xlim(x.min(), x.max())
ax.set_ylim(-10, 110)

plt.show()

结果:

enter image description here

相关问题