matplotlib 如何在两行之间创建水平颜色渐变?

8wtpewkr  于 2023-06-06  发布在  其他
关注(0)|答案(1)|浏览(113)

我想在我的图中的两条线之间做一个颜色渐变,红-蓝。线条是垂直的,而渐变应该是水平的。
具有x(d180)和y(截面高度)的两条线

x1              y1
0  -0.828533           -51.0
3  -0.545964           -16.0
5  -0.761425           -20.0
6  -0.580972            -3.0
8  -0.854383          -162.0
12 -1.364880          -251.0
13 -1.244032          -261.0
18 -0.748652          -305.0
38 -1.300000          -600.0
39 -1.742075          -932.0

and 

          x2              y2
1  -1.309039           -51.0
2  -0.582214           -16.0
4  -1.129269           -20.0
7  -0.974811            -3.0
9  -0.957930          -162.0
10 -1.418976          -251.0
14 -1.664210          -261.0
20 -2.530322          -315.0
37 -1.630000          -600.0
41 -2.291032          -932.0

我尝试制作一个fill_betweenx空多边形,然后填充它,但是渐变是垂直的而不是水平的

cm1 = LinearSegmentedColormap.from_list('Temperature Map', ['blue', 'red'])
polygon = plt.fill_betweenx(y2,x1,x2, lw=0, color='none')

verts = np.vstack([p.vertices for p in polygon.get_paths()])
gradient = plt.imshow(np.linspace(0, 1, 256).reshape(-1, 1), cmap=cm1, aspect='auto', origin='upper',
                      extent=[verts[:, 0].min(), verts[:, 0].max(), verts[:, 1].min(), verts[:, 1].max()])
gradient.set_clip_path(polygon.get_paths()[0], transform=plt.gca().transData)

如何使渐变从左到右而不是从上到下?

bmp9r5qi

bmp9r5qi1#

你只需要改变你的“图像”的方向,所以用np.linspace(0, 1, 256).reshape(1, -1)代替np.linspace(0, 1, 256).reshape(-1, 1)

import numpy as np
import matplotlib.pyplot as plt

from matplotlib.colors import LinearSegmentedColormap

x1 = [-0.828533,
      -0.545964,
      -0.761425,
      -0.580972,
      -0.854383,
      -1.364880,
      -1.244032,
      -0.748652,
      -1.300000,
      -1.742075]

x2 = [-1.309039,
      -0.582214,
      -1.129269,
      -0.974811,
      -0.957930,
      -1.418976,
      -1.664210,
      -2.530322,
      -1.630000,
      -2.291032]

y2 = [-51.0,
      -16.0,
      -20.0,
      -3.0,
      -162.0,
      -251.0,
      -261.0,
      -315.0,
      -600.0,
      -932.0]

cm1 = LinearSegmentedColormap.from_list('Temperature Map', ['blue', 'red'])
polygon = plt.fill_betweenx(y2, x1, x2, lw=0, color='none')

verts = np.vstack([p.vertices for p in polygon.get_paths()])
gradient = plt.imshow(np.linspace(0, 1, 256).reshape(1, -1), cmap=cm1, aspect='auto', origin='upper',
                      extent=[verts[:, 0].min(), verts[:, 0].max(), verts[:, 1].min(), verts[:, 1].max()])
gradient.set_clip_path(polygon.get_paths()[0], transform=plt.gca().transData)

plt.show()

相关问题