批处理matplotlib脚本不保存轴

2024-10-02 14:22:18 发布

您现在位置:Python中文网/ 问答频道 /正文

更新:已解决;请参阅注释。你知道吗

我对matplotlib有点陌生,在使用批处理脚本时,很难输出包含轴的绘图的图像或pdf文件。你知道吗

相关代码如下:

  fig=plt.figure()  
  ax=fig.add_axes([0.1,0.1,0.75,0.75])
  ax.set_xlabel("Radius")
  ax.set_ylabel("Average density")
  ax.plot(nr,ravs,'k-')
#  plt.plot(nr,ravs)
#  plt.ylabel("Average density")
#  plt.xlabel("Radius")
  plt.savefig("outputs/diskgap/rl"+str(ng)+".jpg") 

nr是一个仅包含线性空间半径值的NumPy数组,ravs是一个包含平均密度值的标准1D数组;您可以使用伪数据进行复制。ng只是循环计数器。这是在一个批处理脚本中,从一系列输出文件夹中获取数据,进行打印,并保存打印,同时进行一些分析和输出。你知道吗

我发现,当在IDLE或交互式iPython会话中运行时,这会产生与预期完全一样的输出,但当作为批处理脚本运行时(在终端中,键入“python”)polardisk.py公司'运行脚本),我得到以下输出: Plot with no axes or labels

我应该得到的是:earlier plot saved from plt.show()

我试过摆弄add\u axes或figure()参数,如alpha、transparency、frameon、visibility、edgecolor、linewidth等,但都没有用——我得到了相同的结果。你知道吗

我的预感是,也许轴和标签正在被绘制,但不管出于什么原因,它们被绘制为白色,而不是黑色。这是我以前在IDL遇到的问题。有什么想法吗?你知道吗

编辑:

下面是这个例程访问的数据(只是示例运行,没有真正的科学价值),目的是试图完美地复制我的问题:https://goo.gl/yJ7TW3

下面是完整的脚本:

from matplotlib import pyplot as plt
from matplotlib import cm
import numpy as np

# First, load data from density file into a 2D numpy array

plt.ioff()

ng = 1

masses = []
d=1
while d<=20:
  masses.append(d*0.0001)
  d+=1

gaps=[]

while ng <= 20:

  rho = np.fromfile("outputs/diskgap/gr"+str(ng)+"/gasdens1.dat").reshape(128,384) #or whatever your dimensions are--reshape is r,phi

# Now we need 1D arrays of radii and angles corresponding to each row and column of rho

  nphi = np.linspace(-3.14159265358979323844,3.14159265358979323844,num=384) #1D array of phi values
  nr = np.linspace(0.4,2.5,num=128) #1D array of r values -- set to whatever radial span you used

# Create our plot

  ax = plt.subplot(111,polar=True)
  ax.set_yticklabels([]) #Get rid of radii labels (optional)

# Create polar image

  ctf = ax.contourf(nphi,nr,rho,256,cmap=cm.jet) #256 is the number of colors--using fewer will mean fewer contour levels, and cm.jet is just the colormap.

# Make sure we have a central hole where we didn't have data, rather than drawing nonzero rmin down to center
# This will also plot the polar image onto the plot.

  plt.ylim(0,2.5) #2.5 is just rmax, set to whatever you used

# Add a colorbar (optional)

#plt.colorbar(ctf)

#Save the image, and you're done!

  plt.savefig("outputs/diskgap/gr"+str(ng)+".jpg",bbox_inches='tight')
  plt.savefig("outputs/diskgap/gr"+str(ng)+".pdf",bbox_inches='tight')
  print "Finished disk number "+str(ng)+"!"

  plt.close("all")

  ravs = []

  d=0
  while d<len(rho[:,0]):
    ravs.append(np.mean(rho[d,:]))
    d+=1

  fig=plt.figure()  
  ax=fig.add_axes([0.1,0.1,0.75,0.75])
  ax.set_xlabel("Radius")
  ax.set_ylabel("Average density")
  ax.plot(nr,ravs,'k-')
#  plt.plot(nr,ravs)
#  plt.ylabel("Average density")
#  plt.xlabel("Radius")
  plt.savefig("outputs/diskgap/rl"+str(ng)+".jpg")   
  fig=plt.figure()  
  ax=fig.add_axes([0.1,0.1,0.75,0.75])
  ax.set_xlabel("Radius")
  ax.set_ylabel("Average density")
  ax.plot(nr,ravs,'k-')  
#  plt.plot(nr,ravs)
#  plt.ylabel("Average density")
#  plt.xlabel("Radius")
  plt.savefig("outputs/diskgap/rl"+str(ng)+".pdf",bbox_inches='tight')

  gaps.append(ravs[38]/ravs[100])

  print "Finished analyzing radial profile and gap for set "+str(ng)+"!"
  plt.close("all")
  ng+=1

plt.plot(masses,gaps)
plt.ylabel("Percent deficiency")
plt.xlabel("Planet mass")
plt.savefig("outputs/diskgap/gaps.jpg",bbox_inches='tight')
plt.plot(masses,gaps)
plt.ylabel("Percent deficiency")
plt.xlabel("Planet mass")
plt.savefig("outputs/diskgap/gaps.pdf",bbox_inches='tight') 

脚本与提供的数据在同一目录下运行——outputs/和脚本都在同一目录下。你知道吗


Tags: 脚本plotpltaxdensityngoutputsnr