【发布时间】:2018-02-05 03:10:24
【问题描述】:
我正在根据从 NetCDF 文件中提取的数据绘制一些海洋温度和盐度图。它们被用作我使用moviepy 库制作的动画中的帧。我正在使用的软件包:
from netCDF4 import Dataset # reads netCDF file
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap # basemap tools
from datetime import datetime, timedelta #for working with datetimes
import moviepy.editor as mpy # creates animation
from moviepy.video.io.bindings import mplfig_to_npimage # converts map to numpy array
from matplotlib.backends.backend_agg import FigureCanvasAgg # draws canvas so that map can be converted
当我自己绘制图时,它们看起来很好。这是盐度图的示例。
# map setup
fig = plt.figure()
fig.subplots_adjust(left=0., right=1., bottom=0., top=0.9)
# Setup the map
m = Basemap(projection='merc', llcrnrlat=-38.050653, urcrnrlat=-34.453367,\
llcrnrlon=147.996456, urcrnrlon=152.457344, lat_ts=20, resolution='h')
# draw stuff
m.drawcoastlines()
m.fillcontinents(color='black')
# plot salt
cs = m.pcolor(lons,lats,np.squeeze(salt), latlon = True ,vmin=salt_min, vmax=salt_max, cmap='viridis')
# plot colourbar
plt.colorbar()
# datetime title
plt.title('Regional - Salinity (PSU)\n' + frame_time.strftime("%Y-%m-%d %H:%M:%S") + ' | ' + str(fname) + '_idx: ' + str(frame_idx))
# stop axis from being cropped
plt.tight_layout()
但是我想并排绘制温度和盐度,但是当我这样做时,彩条和数字并没有像我预期的那样绘制。
# set up figure
fig = plt.figure()
fig.subplots_adjust(left=0., right=1., bottom=0., top=0.9)
# Temperature figure
plt.subplot(1, 2, 1)
# Setup the map
m = Basemap(projection='merc', llcrnrlat=-38.050653, urcrnrlat=-34.453367,\
llcrnrlon=147.996456, urcrnrlon=152.457344, lat_ts=20, resolution='h')
# draw stuff
m.drawcoastlines()
m.fillcontinents(color='black')
# plot salt
cs = m.pcolor(lons,lats,np.squeeze(temp), latlon = True ,vmin=temp_min, vmax=temp_max, cmap='plasma')
# plot colourbar
plt.colorbar()
# datetime title
plt.title('Regional - Temperature (Celcius)\n' + frame_time.strftime("%Y-%m-%d %H:%M:%S") + ' | ' + str(fname) + '_idx: ' + str(frame_idx))
# Salinity figure
plt.subplot(1, 2, 2)
# Setup the map
m = Basemap(projection='merc', llcrnrlat=-38.050653, urcrnrlat=-34.453367,\
llcrnrlon=147.996456, urcrnrlon=152.457344, lat_ts=20, resolution='h')
# draw stuff
m.drawcoastlines()
m.fillcontinents(color='black')
# plot salt
cs = m.pcolor(lons,lats,np.squeeze(salt), latlon = True ,vmin=salt_min, vmax=salt_max, cmap='viridis')
# plot colourbar
plt.colorbar()
# datetime title
plt.title('Regional - Salinity (PSU)\n' + frame_time.strftime("%Y-%m-%d %H:%M:%S") + ' | ' + str(fname) + '_idx: ' + str(frame_idx))
# make layout nice
plt.tight_layout()
我希望它们与原始示例相似,但并排放置。我想我正在正确使用 subplot 函数,但我只是不知道如何修复它。有任何想法吗?谢谢。
注意:也许对于这个问题不是必需的,但我可能会提到每一帧都被转换为一个 numpy 数组,因为我稍后将图像传递给 moviepy 中的函数以制作动画。
# convert to array
canvas = FigureCanvasAgg(fig)
canvas.draw()
frame = np.fromstring(canvas.tostring_rgb(), dtype='uint8')
frame = frame.reshape(fig.canvas.get_width_height()[::-1] + (3,))
这是一个输出示例:
【问题讨论】:
标签: python matplotlib plot subplot