Skip to main content
 首页 » 编程设计

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

2024年11月24日10kenshinobiy

我已经成功地将我的 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() 

结果如下:

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

请您参考如下方法:

我稍微更改了您的代码,但主要是将它与 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() 

结果: