【问题标题】:Python Matplotlib Colorbar/Colormap SettingsPython Matplotlib 颜色栏/颜色图设置
【发布时间】:2013-08-03 17:21:15
【问题描述】:

我创建了一个animation of a wave,但颜色条一直在移动,我不知道为什么。我认为这是因为它在每一帧之后都会正常化。如何设置颜色图设置以使颜色条保持不变?

代码:警告:此程序会删除其调用目录中的 png3D 文件夹。制作所有帧也可能需要一段时间,具体取决于您的计算能力。

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import time
import sys,os,shutil
time.clock()

def FUNCTION(p,r,t):
    k_0,dx,c = p
    x,y = r
    x,y = np.meshgrid(x,y)
    r = np.sqrt(x**2 + y**2)
    z = np.exp(1j*(k_0[0]*x+k_0[1]*y-c*t))*np.exp(-((r-c*t)/(2*dx))**2 )*0.5**(r/x[0][-1]/2)
    z = abs(z)
    return(x,y,z)

def PRINT_PNG(x,y,t,folder):
    x,y,z = FUNCTION(p,r,t)

    fig = plt.figure()
    sub = fig.gca(projection='3d')
    fig.suptitle("3D Wavepackage", size="large")
    sub.set_zlim([0,1.5])
    sub.set_xlabel("x",size="large")
    sub.set_ylabel("y",size="large")
    sub.set_zlabel("$Re[\psi(x,t)]$",size="large",ha="right")   
    sub.text(0.5,0.5,0.5,"t = "+str("%3.1f"%t)+" s",transform = sub.transAxes, ha="right")

    surf = sub.plot_surface(x,y,z,linewidth=0,cmap=cm.coolwarm)
    fig.colorbar(surf, shrink=0.5, aspect=5)
    file_name = os.path.abspath(folder+"/tmp"+str("%04d"%i)+".png")
    fig.savefig(file_name)
    plt.close()

# Parameters
T = 10
N = 100
n = 24*T # 24 Frames pro Sekunde
t = np.linspace(0,T,n)
k_0 = [1,1]
dx  = 1
c   = 1
p = [k_0,dx,c]

x   = np.linspace(-c*T,c*T,N)
y   = np.linspace(-c*T,c*T,N)
r=[x,y]


# Baue Ordner
folder = os.path.abspath("png3D")
if os.path.exists(folder)==True:
    shutil.rmtree(folder)
    os.makedirs(folder)
else:
    os.makedirs(folder)

for i in range(n):
    PRINT_PNG(x,y,t[i],folder)
    print(str(i+1)+"/"+str(n))

file_name = os.path.abspath("png3D//tmp%04d.png")
os.system("ffmpeg -f image2 -y -i "+file_name+" -r 24 -bit_rate 1800 3D_Wave.mpeg")
shutil.rmtree(folder)
print(time.clock())

【问题讨论】:

  • 虽然我很乐意提供示例代码,但最好将代码简化为 a) 快速运行 b) 不与本地文件混为一谈。
  • 我看不出有什么办法可以做到这一点。我尝试使用 matplotlib 的动画模块,但它部分不适用于 python 3.3,并且不支持某些 3D 绘图(似乎)。因此,如果没有电影或动画,我该如何简单地编写不先保存电影图像的代码?

标签: python matplotlib colorbar


【解决方案1】:

您可以将vminvmax 关键字参数传递给plot_surface,为您的绘图指定值范围:

surf = sub.plot_surface(x,y,z,linewidth=0,cmap=cm.coolwarm,vmin=0,vmax=1)

请参阅the docs 了解更多信息。

【讨论】:

  • 绘制完surf.set_clim([vmin, vmax])也可以使用。
  • 这正是我需要的,谢谢。在战略问题上:您是碰巧知道这一点,还是在某个地方查到了这一点?我查看了 matplotlib 文档,但找不到此设置。
  • 这是个好问题。我通过使用imshow 知道vminvmax 关键字参数,因此在matplotlib 网站上搜索plot_surface 并看到这些已列出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-24
  • 1970-01-01
  • 2012-04-11
  • 1970-01-01
  • 2014-10-19
  • 1970-01-01
相关资源
最近更新 更多