matplotlib:使用对数颜色条值着色2D线,用于对散点图进行着色

时间:2015-04-30 05:12:19

标签: python matplotlib

我需要为连接由第3个变量着色的散点图的线条着色(第三个变量对于所有散点都是相同的;我将在末尾有多个散点图和不同的第三个变量)。我需要线的颜色来匹配散点,并且颜色条需要进行日志缩放。我无法提取用于为散点图上色的RGBA对数标准化值,以便按该值为线条着色。示例如下:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

color = plt.get_cmap('Blues')

#Fake data
a = np.arange(0,10,1)
b = np.arange(10,20,1)
d = [100]*10

maxval=1000.0
minval=10.0

#Normalize array to limits of colorbar
l=d[1]
normalized= (l/(maxval-minval))

#Check if Nan (I have some NaN's).
#Returns the colormap value
check = np.isnan(np.sum(normalized))
cmapvalue=[]
if check==True:
    cmapvalue=g
else:
    cmapvalue=color(normalized)

#Plot scatter and line, line needs to be colored by RGBA value used to color scatter points
plt.scatter(a, b, c=d, cmap=color, norm=mpl.colors.LogNorm(vmax=maxval,       vmin=minval), zorder=2, s=50)
plt.plot(a,b, c=cmapvalue, zorder=1, lw=4)

plt.colorbar()
plt.show()

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

所以问题是您可以线性(手动)缩放数值。但是在散布调用中,您传递了一个对数缩放类。您可以直接使用它来规范化调用绘图的值:

,而不仅仅是传递它
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

#Fake data
a = np.arange(0,10,1)
b = np.arange(10,20,1)
d = [50]*10

# define vmin and vmax
maxval=1000.0
minval=10.0

# build up colormap and normalizer
colormap = plt.get_cmap('Blues')
norm = mpl.colors.LogNorm(vmax=maxval, vmin=minval)

# helper function to plot the line and the scatter data
def plot_my_scatterdata(x, y, d):
    if np.any(np.isnan(d)):
        color = 'g'
    else:
        # use the colormap and the normalization instance!
        color = colormap(norm(d[0]))

    plt.scatter(a, b, c=d, cmap=colormap, norm=norm, zorder=2, s=50)
    plt.plot(a,b, '-', color=color, zorder=1, lw=4)

plot_my_scatterdata(a, b, d)
d = [100]*10
b += 1
plot_my_scatterdata(a, b, d)
d = [500]*10
b += 1
plot_my_scatterdata(a, b, d)
d[0] = np.nan
b += 1
plot_my_scatterdata(a, b, d)

plt.colorbar()
plt.show()

结果: enter image description here