我使用matplotlib.pyplot
制作了contourf
图。现在我想要一条水平线(或者类似 ax.vspan 的东西也可以),并在 y = 0 处进行条件着色。我会告诉你我拥有什么以及我想得到什么。我想用一个数组来做到这一点,比如说代表陆地、海洋或冰的landsurface
。该数组填充有 1
(陆地)、2
(海洋)或 3
(冰),并具有 len(locs)
(x 轴)。
这是情节代码:
plt.figure()
ax=plt.axes()
clev=np.arange(0.,50.,.5)
plt.contourf(locs,height-surfaceheight,var,clev,extend='max')
plt.xlabel('Location')
plt.ylabel('Height above ground level [m]')
cbar = plt.colorbar()
cbar.ax.set_ylabel('o3 mixing ratio [ppb]')
plt.show()
这是我到目前为止所拥有的:
这就是我想要的:
非常感谢!
最佳答案
简介
我将使用line collection .
因为我没有你的原始数据,所以我使用简单的正弦曲线伪造了一些数据,并在基线上绘制了与曲线的小、中、高值相对应的颜色代码
代码
通常的样板,我们需要显式导入LineCollection
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import LineCollection
只是为了绘制一些东西,正弦曲线(x r
x = np.linspace(0, 50, 101)
y = np.sin(0.3*x)
从曲线值(对应于您的曲面类型)到 LineCollection
颜色的颜色编码,请注意,LineCollection
要求颜色被指定为 RGBA 元组,但我见过使用颜色字符串的示例,呸!
# 1 when near min, 2 when near 0, 3 when near max
z = np.where(y<-0.5, 1, np.where(y<+0.5, 2, 3))
col_d = {1:(0.4, 0.4, 1.0, 1), # blue, near min
2:(0.4, 1.0, 0.4, 1), # green, near zero
3:(1.0, 0.4, 0.4, 1)} # red, near max
# prepare the list of colors
colors = [col_d[n] for n in z]
在行集合中,我们需要一系列段,这里我决定将编码行放在 y=0
处,但您只需向 s
添加一个常量即可上下移动它。
我承认形成片段序列有点棘手......
# build the sequence of segments
s = np.zeros(101)
segments=np.array(list(zip(zip(x,x[1:]),zip(s,s[1:])))).transpose((0,2,1))
# and fill the LineCollection
lc = LineCollection(segments, colors=colors, linewidths=5,
antialiaseds=0, # to prevent artifacts between lines
zorder=3 # to force drawing over the curve) lc = LineCollection(segments, colors=colors, linewidths=5) # possibly add zorder=...
最后,我们将所有内容都放在 Canvas 上
# plot the function and the line collection
fig, ax = plt.subplots()
ax.plot(x,y)
ax.add_collection(lc)
关于python - 添加带条件着色的水平线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56001070/