matplotlib 带错误条的Python颜色条

ulydmbyx  于 2022-12-30  发布在  Python
关注(0)|答案(1)|浏览(105)

我正在尝试绘制x与y数据,并尝试使用颜色条查看x和y相对于z的变化。

x = [1,2,3,4,5]
x_err = [0.1,0.2,0.3,0.4,0.5]
y = [5,6,7,8,9]
y_err = [0.5,0.6,0.7,0.8,0.9]
z = [3,4,5,6,7]

fig, ax = plt.subplots()

ax.errorbar(x, y, x_err, y_err, fmt='*', elinewidth = 0.9, ecolor='black')

scatter = ax.scatter(x, y, c=z, s=5)
cbar = fig.colorbar(scatter,cmap='viridis')
cbar.set_label('z')

我需要错误栏的颜色与数据点的颜色相同。

8hhllhi2

8hhllhi21#

您可以从相同的cmap计算ecolor,不确定是否有任何解决方案可以为您完成此操作,但成本并不高

import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np

x = [1,2,3,4,5]
x_err = [0.1,0.2,0.3,0.4,0.5]
y = [5,6,7,8,9]
y_err = [0.5,0.6,0.7,0.8,0.9]
z = [3,4,5,6,7]

fig, ax = plt.subplots()

# Rest of your code is yours. Only this line is added (and next line modified to use this "col" as ecolor
col=cm.viridis((np.array(z)-min(z))/(max(z)-min(z))) # RGBA colors from z
ax.errorbar(x, y, x_err, y_err, ecolor=col, fmt='*', elinewidth = 0.9)

scatter = ax.scatter(x, y, c=z, s=5)
cbar = fig.colorbar(scatter,cmap='viridis')
cbar.set_label('z')

plt.show()

结果

相关问题