2D彩色编码散点图,具有用户定义的颜色范围和静态色彩映射

时间:2015-08-13 03:11:13

标签: python numpy matplotlib scatter-plot

我有3个向量 - xyvel,每个向量都有8k值。我也有很多包含这3个载体的文件。所有文件都有不同的x,y,vel。我想获得具有以下条件的多个散点图:

  1. 根据第3个变量,即vel。
  2. 进行颜色编码
  3. 一旦为颜色设置了范围(对于第一个文件中的数据),它们应对所有剩余文件保持不变。我不想动态改变(每个新文件的颜色代码都在变化)。
  4. 想要绘制一个颜色条。
  5. 我非常感谢你的所有想法!!

    我附上了单个文件的代码。

    import numpy as np
    import matplotlib.pyplot as plt
    
    # Create Map
    cm = plt.cm.get_cmap('RdYlBu')
    x,y,vel = np.loadtxt('finaldata_temp.txt', skiprows=0, unpack=True)
    vel = [cm(float(i)/(8000)) for i in xrange(8000)] # 8000 is the no. of values in each of x,y,vel vectors.
    
    # 2D Plot
    plt.scatter(x, y, s=27, c=vel, marker='o')
    plt.axis('equal')
    plt.savefig('testfig.png', dpi=300)
    plt.show()
    quit()
    

1 个答案:

答案 0 :(得分:0)

您必须迭代所有数据文件才能获得vel的最大值,我添加了几行代码(需要调整以适应您的情况)才会这样做。

因此,您的colorbar行已更改为使用max_vel,允许您使用8000的固定值删除该代码。

此外,我冒昧地删除了点周围的黑边,因为我发现它们会混淆'点的颜色。

最后,我添加了调整您的绘图代码以使用axis对象,这需要有一个颜色条。

import numpy as np
import matplotlib.pyplot as plt
# This is needed to iterate over your data files
import glob 

# Loop over all your data files to get the maximum value for 'vel'. 
# You will have to adjust this for your code
"""max_vel = 0
for i in glob.glob(<your files>,'r') as fr:
    # Iterate over all lines
    if <vel value> > max_vel:
        max_vel = <vel_value>"""

# Create Map
cm = plt.cm.get_cmap('RdYlBu')
x,y,vel = np.loadtxt('finaldata_temp.txt', skiprows=0, unpack=True)

# Plot the data
fig=plt.figure()
fig.patch.set_facecolor('white')
# Here we switch to an axis object
# Additionally, you can plot several of your files in the same figure using
# the subplot option.
ax=fig.add_subplot(111)
s = ax.scatter(x,y,c=vel,edgecolor=''))
# Here we assign the color bar to the axis object
cb = plt.colorbar(mappable=s,ax=ax,cmap=cm)
# Here we set the range of the color bar based on the maximum observed value
# NOTE: This line only changes the calculated color and not the display 
# 'range' of the legend next to the plot, for that we need to switch to 
# ColorbarBase (see second code snippet).
cb.setlim(0,max_vel)
cb.set_label('Value of \'vel\'')
plt.show()

摘录,演示ColorbarBase

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

cm = plt.cm.get_cmap('RdYlBu')
x = [1,5,10]
y = [2,6,9]
vel = [7,2,1]

# Plot the data
fig=plt.figure()
fig.patch.set_facecolor('white')
ax=fig.add_subplot(111)
s = ax.scatter(x,y,c=vel,edgecolor=''))
norm = mpl.colors.Normalize(vmin=0, vmax=10)
ax1 = fig.add_axes([0.95, 0.1, 0.01, 0.8])
cb = mpl.colorbar.ColorbarBase(ax1,norm=norm,cmap=cm,orientation='vertical')
cb.set_clim(vmin = 0, vmax = 10)
cb.set_label('Value of \'vel\'')
plt.show()

这会生成以下图

Matplotlib plot of sample data using ColorbarBase

有关使用colorbar可以执行的操作的更多示例,特别是更灵活的ColorbarBase,我建议您查看文档 - &gt; http://matplotlib.org/examples/api/colorbar_only.html

相关问题