python - matplotlib.pyplot 二维参数的颜色图图例
问题描述
我正在同一轴上绘制一系列均方位移 (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
值水平。我该如何实施?谢谢!
解决方案
也许一张桌子可以完成这项工作:
#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()
推荐阅读
- c# - 截图最小化窗口,不使用win32的PrintWindow
- python - 创建一个新行,它是上面行的计算结果 - Pandas DataFrame
- javascript - Date-fns RangeError:时间值无效
- java - 错误 500:实例化 servlet 类时出错
- android - 在没有推送通知的情况下更新应用程序图标上的徽章计数
- html - 为什么内部弹性宽度溢出?
- prolog - Prolog - 使用累加器查找第 N 个斐波那契数
- javascript - React setState:回调子组件的功能
- python - 给定具有两个纬度/经度值的DataFrame,如何使用geopandas返回多行
- android - 尝试在空对象引用上调用虚拟方法“void androidx.recyclerview.widget.RecyclerView.setLayoutManager()”