【问题标题】:matplotlib.pyplot Colormap legend for 2D parametermatplotlib.pyplot 二维参数的颜色图图例
【发布时间】:2020-05-11 15:13:38
【问题描述】:

我正在同一轴上绘制一系列均方位移 (MSD) 对数图,用于模拟自推进粒子。对于传递标准偏差Dtrans = [0.1, 0.3, 1.0, 3.0, 10] 和旋转标准偏差Drot = [0.1, 0.3, 1.0, 3.0, 10, 30, 100, 300],模拟运行不同的值,总共进行了 5 × 8 = 40 次模拟。这是我目前拥有的:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import itertools

# List of colour maps
cmaps = ['YlOrRd', 'Greens', 'Blues', 'Purples','RdPu']

nparticles = 5
npts=1000
step=1000
dt = 0.0001

Drot = [0.1, 0.3, 1.0, 3.0, 10, 30, 100, 300]
Dtrans = [0.1, 0.3, 1.0, 3.0, 10]

plt.figure()
plt.title('MSD against time')
plt.xlabel('Time')
plt.ylabel('MSD')

# Time steps along horizontal axis:
timeval = np.linspace(0,dt*step*(npts-1),npts)

# For each value of Dtrans
for d1 in range(len(Dtrans)):

    # Choose a colour map:
    colourmap = plt.get_cmap(cmaps[d1])
    # Limit it to the middle 60%
    colourmap = colors.ListedColormap(colourmap(np.linspace(0.2, 0.8, 256)))

    # Get a colour from the map for each value of Drot:
    values = range(len(Drot))
    cNorm = colors.Normalize(vmin=0,vmax=values[-1])
    scalarMap=cmx.ScalarMappable(norm=cNorm,cmap=colourmap)

    for d2 in range(len(Drot)):
        Dr = Drot[d2]
        Dt = Dtrans[d1]
        MSD = np.zeros((npts,))

        x = np.zeros((npts,nparticles))
        y = np.zeros((npts,nparticles))
        for k in range(npts):
            data0=np.loadtxt(open("./Lowdensity/Drot_"+str(Dr)+"/Dtrans_"+str(Dt)+"/ParticleData/ParticleData"+str(k*step)+".csv",'rb'),delimiter=',')
            x0,y0= data0[:nparticles,1],data0[:nparticles,2]
            x[k,:]=x0
            y[k,:]=y0

        for k in range(npts):
            MSD[k] = np.mean(np.mean((x[k:npts,:] - x[0:(npts-k),:])**2 + (y[k:npts,:] - y[0:(npts-k),:])**2,axis=0))

        colorVal = scalarMap.to_rgba(values[d2])

        plt.loglog(timeval,MSD,color=colorVal)
        plt.legend([('Dtrans='+str(i)+', Drot='+str(j)) for [i,j] in np.array(list(itertools.product(Dtrans,Drot)))])

#plt.loglog(timeval, MSDthry(timeval, 0.5, 100, 70, dt*step*npts))
plt.show()

色彩图效果很好,但我目前的传说真的很可怕,不适合情节。理想情况下,我希望图例是垂直排列的五个颜色条,Dtrans 值沿垂直轴,Drot 值水平排列。我该如何实施?谢谢!

【问题讨论】:

  • 您将创建一个插入轴,其中包含一个显示您喜欢的颜色的 imshow 图。
  • 你看到这个问题了吗,stackoverflow.com/q/38647370/12744275 即使它不是你所期望的那样,我认为这是一个好的开始

标签: python matplotlib colorbar colormap color-mapping


【解决方案1】:

也许一张桌子可以完成这项工作:

#initialyze an array at the beginning 
colorsarray = np.empty([5,5] )
for d1 in range(len(Dtrans)):
    ...     
    colorVal = scalarMap.to_rgba(values[d2]) 
    colorsarray[d1, d2] =colorVal

    plt.loglog(timeval,MSD,color=colorVal) 


tab=plt.table(cellText="" , colLabels=Dtrans, 
    rowLabels=Drot, colWidths = [0.2,0.2], 
    loc='higher left', cellColours=colorsarray )
plt.show()

【讨论】:

    【解决方案2】:

    我自己解决了,但为了完整起见,这是我的解决方案。

    与 Renaud 的解决方案一样,我为颜色初始化了一个矩阵,但将它们放在热图中而不是表格中。我正在使用plt.subplot 在图表旁边绘制热图。

    colorsarray = np.empty((len(Dtrans),len(Drot)),dtype=(float,4))
    
    fig=plt.figure()
    gs=fig.add_gridspec(3,3)
    
    ax1 = fig.add_subplot(gs[:,:-1])
    ax2 = fig.add_subplot(gs[1,2])
    
    for d1 in range(len(Dtrans)):
        ...
        colorVal = scalarMap.to_rgba(values[d2])
        colorsarray[d1, d2] = colorVal
    
        ax1.loglog(timeval,MSD,color=colorVal)
    
    plt.setp(ax2.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor")
    ax2.imshow(colorsarray,interpolation=None)
    ax2.set_xticks(np.arange(len(Drot)))
    ax2.set_yticks(np.arange(len(Dtrans)))
    ax2.set_xticklabels(Drot)
    ax2.set_yticklabels(Dtrans)
    ax2.set_xlabel('D_rot')
    ax2.set_ylabel('D_trans')
    ax2.axis('equal')
    
    plt.tight_layout()
    plt.show()
    

    我使用了this 关于热图的文章。

    【讨论】:

      猜你喜欢
      • 2015-09-27
      • 1970-01-01
      • 2014-02-18
      • 2012-08-09
      • 1970-01-01
      • 2011-09-10
      • 1970-01-01
      • 2016-06-26
      • 1970-01-01
      相关资源
      最近更新 更多