The quest isto save the figure, which shows in jupyter, but can`t be saved. I have tried lots of things.
The code to reproduce (just copy-paste):
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline
from scipy.optimize import fsolve
import ast
from mpl_toolkits.axisartist.parasite_axes import HostAxes, ParasiteAxes
import matplotlib.pyplot as plt
basicDict = {'Model_Name': 'TestPump_d258', 'max_pressure': ' 16 бар', 'liquid_pump_temp': ' -15C-110C', 'max_env_temp': ' 40С', 'engine_efficiency_class': ' IE2', 'Net_connection': ' 3~380V/50 Hz', 'rotation_frequency_nominal': ' 2900 1/min', 'Nominal_power_P2': ' P2 15 кВт', 'Nominal_currency': ' 27 А', 'Moisture_protection': ' IP54', 'Isolation_Class': ' F', 'Sucking_pipe_branch': ' DN100', 'Pushing_pipe_branch': ' DN100', 'building_length': ' 480 мм', 'frame': ' GG20', 'working_wheel': ' GG20', 'Shaft': ' 1.4021', 'Weight': ' 335 ', 'flow_rate_Q_m3_h': '[0.00, 11.77, 23.54, 35.31, 47.07, 58.84, 70.61, 82.38, 94.15, 96.04, 105.92, 117.69, 129.45, 141.22, 152.99, 164.76]', 'lift_H_m': '[22.96, 22.92, 22.93, 22.92, 22.80, 22.51, 22.02, 21.28, 20.27, 20.08, 18.98, 17.40, 15.55, 13.45, 11.14, 8.65]', 'Cavitation_NPSH_m': '[1.14, 1.17, 1.20, 1.24, 1.29, 1.37, 1.46, 1.59, 1.76, 1.79, 1.98, 2.26, 2.61, 3.05, 3.58, 4.23]', 'motor_power_P2_kW': '[3.57, 3.84, 4.21, 4.67, 5.17, 5.68, 6.20, 6.70, 7.17, 7.24, 7.60, 7.99, 8.35, 8.67, 8.98, 9.28]', 'efficiency': '[0.00, 4.00, 8.00, 12.00, 16.00, 20.00, 24.00, 28.00, 32.00, 36.00, 40.00, 44.00, 41.00, 38.00, 35.00, 32.00]', 'Scale_Table': '{"L":500,"B":430,"H":855,"C1":160,"B1":220,"A":160,"C2":120,"B2":180,"4-d 1":"4-18"}', 'pump_wiring_connection_figure': 'connection_figures/test_connection.png', 'pump_figure': 'pump_figures/Test_pump_image.png'}
Q = 100
H = 18
flow_rate_Q_m3_h = np.array(ast.literal_eval(basicDict["flow_rate_Q_m3_h"]))
lift_H_m = np.array(ast.literal_eval(basicDict["lift_H_m"]))
Cavitation_NPSH_m = np.array(ast.literal_eval(basicDict["Cavitation_NPSH_m"]))
motor_power_P2_kW = np.array(ast.literal_eval(basicDict["motor_power_P2_kW"]))
efficiency = np.array(ast.literal_eval(basicDict["efficiency"]))
def Formula(Q, H, EfficiancyValue):
Hvx =(((Q/100*EfficiancyValue)/Q)**2)*H
return Hvx
def calculate_Hvx_Line(Q, H, EfficiancyMax):
calculatedPoints = []
percents = range(0,EfficiancyMax)
for each in percents:
calculatedPoints.append(Formula(Q, H, each))
return calculatedPoints
#Строим модели полиномиальной регрессии для данных
model5 = np.poly1d (np.polyfit (flow_rate_Q_m3_h, lift_H_m , 6))
# на графике будет сглаженая, построеная по модели версия
pumpcurve1 = []
for each in range(int(flow_rate_Q_m3_h.max())):
pumpcurve1.append(model5(each))
# график по расчету
calculatedPoints = np.array(calculate_Hvx_Line(Q, H, 120))
#Ищем x точки соприкосновения двух моделей
def F(k):
return Formula(Q, H, k)-model5(k)
Qnew = fsolve(F, 42)[0]
# y точки соприкосновения двух моделей
h = Formula(Q, H, Qnew)
# плотим графики и точку
fig = plt.figure()
host = fig.add_axes([1.2, 1.2, 1.2, 1.2], axes_class=HostAxes)
par1 = ParasiteAxes(host, sharex=host)
par2 = ParasiteAxes(host, sharex=host)
host.parasites.append(par1)
host.parasites.append(par2)
host.axis["right"].set_visible(False)
par1.axis["right"].set_visible(True)
par1.axis["right"].major_ticklabels.set_visible(True)
par1.axis["right"].label.set_visible(True)
# плотим графики и точку
p1, = host.plot([Qnew], [h], 'o', markersize=8, color = "r")
p1, = host.plot([Qnew], [h], 'o', markersize=3, color = "k")
p1, = host.plot(np.linspace(0, 120,120),calculatedPoints, label="calculated")
p1, = host.plot(np.linspace(0, len(pumpcurve1),len(pumpcurve1)),pumpcurve1, label="flow_rate_Q_m3_h")
max_x = (int(np.array(flow_rate_Q_m3_h).max())//10)*(10)+10
host.set_xlim([0,max_x])
host.plot([0, Qnew],[h, h], "k--")
host.text(2, h-1,
fr"h (m) = {h:.2f}", color="k",fontsize=10)
max_y = (int(np.array(calculatedPoints).max())//5)*(5+1)
host.set_ylim([0,max_y])
host.plot([Qnew, Qnew],[0, h], "k--")
host.text(Qnew + 2, 0.5,
fr"Q (m$^3$/s) = {Qnew:.2f}", color="k")
p2, = par2.plot(np.linspace(0, np.max(flow_rate_Q_m3_h),len(flow_rate_Q_m3_h)),efficiency, label="efficiency")
ef_max = (int(np.array(efficiency).max())//5)*(5+1)
par1.set_ylim(0, ef_max)
host.set_xlabel(r'Q (m$^3$/s)')
host.set_ylabel('h (m)')
par1.set_ylabel("efficiency (%)")
host.legend()
host.grid(True)
host.axis["left"].label.set_color(p1.get_color())
par1.axis["right"].label.set_color(p2.get_color())
plt.show()
Jupyter output looks like that:
plot examplpe
Although saving can not be achieved, but I have tried lots of ideas, which save blank white image unfortunately
All the things I have tryed:
import cv2 as cv
from PIL import Image, ImageFilter
fig1 = plt.gcf()
plt.draw()
fig1.savefig('im.png')
width, height = fig.get_size_inches() * fig.get_dpi()
width , height = int(width), int(height)
Also
canvas = FigureCanvas(fig)
canvas.draw()
buf = canvas.buffer_rgba()
X = np.asarray(buf)
cv.imshow("ready",X.reshape(height, width,4))
Also
canvas = FigureCanvas(fig)
image = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
cv.imshow("ready",image.reshape(height, width, 3))
this is also blank
def fig2img(fig):
"""Convert a Matplotlib figure to a PIL Image and return it"""
import io
buf = io.BytesIO()
fig.savefig(buf)
buf.seek(0)
img = Image.open(buf)
return img
im = np.uint8(fig2img(fig))
cv.imshow("ready",im)
cv.waitKey(00)
found.
The plot was moved from camera or smth. Needed to change line from
host = fig.add_axes([1.2, 1.2, 1.2, 1.2], axes_class=HostAxes)
to
host = fig.add_axes([0.15, 0.1, 0.65, 0.8], axes_class=HostAxes)
Related
I'm trying to animate a scatterplot but get the following error. I had it working previously but its now returning this error on repeat.
ValueError: 'vertices' must be a 2D list or array with shape Nx2
I'll attach the animation code below. I had it working before so know it works.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import matplotlib.transforms as transforms
XA = np.random.randint(80, size=(1000, 15))
YA = np.random.randint(80, size=(1000, 15))
XB = np.random.randint(80, size=(1000, 15))
YB = np.random.randint(80, size=(1000, 15))
XC = np.random.randint(80, size=(1000, 1))
YC = np.random.randint(80, size=(1000, 1))
fig, ax = plt.subplots(figsize = (10,6))
ax.axis('equal')
'''' Scatter Plot '''
scatter_A = ax.scatter(XA[0], YA[0], c=['blue'], alpha = 0.7, s = 20, edgecolor = 'black', zorder = 2)
scatter_B = ax.scatter(XB[0], YB[0], c=['white'], alpha = 0.7, s = 20, edgecolor = 'black', zorder = 2)
offset = lambda p: transforms.ScaledTranslation(p/82.,0, plt.gcf().dpi_scale_trans)
trans = plt.gca().transData
scatter_C = ax.scatter(XC[0], YC[0], c=['red'], marker = 'o', alpha = 0.7, s = 10, edgecolor = 'black', zorder = 2,transform=trans+offset(+2))
'''Animate Function '''
def animate(i) :
scatter_A.set_offsets([[[[[[[[[[[[[[[XA[0+i][0], YA[0+i][0]], [XA[0+i][1], YA[0+i][1]], [XA[0+i][2], YA[0+i][2]], [XA[0+i][3], YA[0+i][3]], [XA[0+i][4], YA[0+i][4]],[XA[0+i][5], YA[0+i][5]], [XA[0+i][6], YA[0+i][6]], [XA[0+i][7], YA[0+i][7]], [XA[0+i][8], YA[0+i][8]], [XA[0+i][9], YA[0+i][9]], [XA[0+i][10], YA[0+i][10]], [XA[0+i][11], YA[0+i][11]], [XA[0+i][12], YA[0+i][12]], [XA[0+i][13], YA[0+i][13]], [XA[0+i][14], YA[0+i][14]]]]]]]]]]]]]]]])
scatter_B.set_offsets([[[[[[[[[[[[[[[XB[0+i][0], YB[0+i][0]], [XB[0+i][1], YB[0+i][1]], [XB[0+i][2], YB[0+i][2]], [XB[0+i][3], YB[0+i][3]], [XB[0+i][4], YB[0+i][4]],[XB[0+i][5], YB[0+i][5]], [XB[0+i][6], YB[0+i][6]], [XB[0+i][7], YB[0+i][7]], [XB[0+i][8], YB[0+i][8]], [XB[0+i][9], YB[0+i][9]], [XB[0+i][10], YB[0+i][10]], [XB[0+i][11], YB[0+i][11]], [XB[0+i][12], YB[0+i][12]], [XB[0+i][13], YB[0+i][13]], [XB[0+i][14], YB[0+i][14]]]]]]]]]]]]]]]])
scatter_C.set_offsets([[XC[0+i][0], YC[0+i][0]]])
ani = animation.FuncAnimation(fig, animate, np.arange(0,1000),
interval = 100, blit = False)
Writer = animation.writers['ffmpeg']
writer = Writer(fps = 10, bitrate = 8000)
ax.autoscale()
plt.draw()
I am running Spyder 3.1.2 through Anaconda 1.6.4, Python 3.5, Python 5.1.0
The error message should give you all the hints you need. Removing the redundant brackets in your set_offsets() calls does the trick:
def animate(i) :
scatter_A.set_offsets([[XA[0+i][0], YA[0+i][0]], [XA[0+i][1], YA[0+i][1]], [XA[0+i][2], YA[0+i][2]], [XA[0+i][3], YA[0+i][3]], [XA[0+i][4], YA[0+i][4]],[XA[0+i][5], YA[0+i][5]], [XA[0+i][6], YA[0+i][6]], [XA[0+i][7], YA[0+i][7]], [XA[0+i][8], YA[0+i][8]], [XA[0+i][9], YA[0+i][9]], [XA[0+i][10], YA[0+i][10]], [XA[0+i][11], YA[0+i][11]], [XA[0+i][12], YA[0+i][12]], [XA[0+i][13], YA[0+i][13]], [XA[0+i][14], YA[0+i][14]]])
scatter_B.set_offsets([[XB[0+i][0], YB[0+i][0]], [XB[0+i][1], YB[0+i][1]], [XB[0+i][2], YB[0+i][2]], [XB[0+i][3], YB[0+i][3]], [XB[0+i][4], YB[0+i][4]],[XB[0+i][5], YB[0+i][5]], [XB[0+i][6], YB[0+i][6]], [XB[0+i][7], YB[0+i][7]], [XB[0+i][8], YB[0+i][8]], [XB[0+i][9], YB[0+i][9]], [XB[0+i][10], YB[0+i][10]], [XB[0+i][11], YB[0+i][11]], [XB[0+i][12], YB[0+i][12]], [XB[0+i][13], YB[0+i][13]], [XB[0+i][14], YB[0+i][14]]])
scatter_C.set_offsets([[XC[0+i][0], YC[0+i][0]]])
I'm surprised that your code worked before. Note that I'm not running exactly the same setup, I'm on macosx 10.13.5 with Python 3.6 installed through macports.
As the title, only white image is printed.
below is my codes
import numpy as np
from vispy import io, scene
c = scene.SceneCanvas(keys='interactive', bgcolor='w', dpi=96)
view = c.central_widget.add_view()
xx, yy = np.arange(-1,1,.02),np.arange(-1,1,.02)
X,Y = np.meshgrid(xx,yy)
R = np.sqrt(X**2+Y**2)
Z = lambda t : 0.1*np.sin(10*R-2*np.pi*t)
surf = scene.visuals.SurfacePlot(xx, yy, Z(0), color=[0.5, 0.5, 0.5], shading='smooth')
view.add(surf)
img = c.render()
io.write_png("vispytest.png", img)
And I get vispytest.png
I'm using Xvfb on Linux.
Xvfb :1 -screen 0 2500x1500x24 -auth localhost
Thank you.
The problem is the focus of the camera, must modify, something similar to the following:
view.camera = scene.TurntableCamera(up='z', fov=60)
Complete code:
import numpy as np
from vispy import io, scene
c = scene.SceneCanvas(keys='interactive', bgcolor='w', dpi=96)
view = c.central_widget.add_view()
view.camera = scene.TurntableCamera(up='z', fov=60)
xx, yy = np.arange(-1,1,.02),np.arange(-1,1,.02)
X,Y = np.meshgrid(xx,yy)
R = np.sqrt(X**2+Y**2)
Z = lambda t : 0.1*np.sin(10*R-2*np.pi*t)
surf = scene.visuals.SurfacePlot(xx, yy, Z(0), color=[0.5, 0.5, 0.5], shading='smooth')
view.add(surf)
img = c.render()
io.write_png("vispytest.png", img)
vispytest.png
i am new to python. I am writing a data logging program and want to open a serial port, then read from it.
My problem is that calling this in my main():
# Handle serial
ser = serial.Serial(strPort, 9600)
doesnt allow me to invoke methods on the ser handle in other functions. Should i make a class or whats the best approach?
Here is the error message:
line 164, in updateData
line = ser.readline().rstrip()
NameError: name 'ser' is not defined
Here is the code:
# Uncomment the next two lines if you want to save the animation
import matplotlib
# matplotlib.use("Agg")
import sys
import serial
import argparse
import csv
import numpy
from matplotlib.pylab import *
from mpl_toolkits.axes_grid1 import host_subplot
import matplotlib.animation as animation
'''
ax03.legend([p031,p032], [p031.get_label(),p032.get_label()])
'''
def main():
# Sent for figure
font = {'size': 9}
matplotlib.rc('font', **font)
# Setup figure and subplots
f0 = figure(num=0, figsize=(12, 10)) # , dpi = 100)
f0.suptitle("Sensor Data", fontsize=12)
ax01 = subplot2grid((3, 2), (1, 0))
#ax02 = subplot2grid((4, 2), (1, 1))
ax02 = ax01.twinx()
ax03 = subplot2grid((3, 2), (0, 0), colspan=2, rowspan=1)
ax04 = subplot2grid((3, 2), (1, 1))
ax05 = subplot2grid((3, 2), (2, 0))
ax06 = subplot2grid((3, 2), (2, 1))
subplots_adjust(left=None, bottom=None, right=None,
top=None, wspace=0.3, hspace=0.3)
# Set titles of subplots
ax01.set_title('Heart Rate Quality and Sample Frequency')
ax03.set_title('Heart Rate')
ax04.set_title('Step Rate')
ax05.set_title('Perfusion Index')
ax06.set_title('Raw PPG')
# set y-limits
ax01.set_ylim(-1, 5)
ax02.set_ylim(100, 500)
ax03.set_ylim(30, 140)
ax04.set_ylim(-50, 250)
ax05.set_ylim(0, 500)
ax06.set_ylim(0, 50000)
# sex x-limits
ax01.set_xlim(0, 50.0)
# ax02.set_xlim(0,50.0)
ax03.set_xlim(0, 50.0)
ax04.set_xlim(0, 50.0)
ax05.set_xlim(0, 50.0)
ax06.set_xlim(0, 50.0)
# Turn on grids
ax01.grid(True)
# ax02.grid(True)
ax03.grid(True)
ax04.grid(True)
ax05.grid(True)
ax06.grid(True)
# set label names
ax01.set_xlabel("t[s]")
ax01.set_ylabel("HRQ")
ax02.set_xlabel("t[s]")
ax02.set_ylabel("samples[Hz]")
ax03.set_xlabel("t[s]")
ax03.set_ylabel("bpm")
ax04.set_xlabel("t[s]")
ax04.set_ylabel("Steps/min")
ax05.set_xlabel("t[s]")
ax05.set_ylabel("AC/DC ratio")
ax06.set_xlabel("t[s]")
ax06.set_ylabel("raw PS sample")
# Data Placeholders
t = zeros(0)
hr = zeros(0)
HRQ = zeros(0)
Fs = zeros(0)
stepRate = zeros(0)
ADCGain = zeros(0)
pI = zeros(0)
rawPPG = zeros(0)
ser = zeros(0)
# set plots
p011, = ax01.plot(t, HRQ, 'c-', label="HRQ", linewidth=2)
p021, = ax02.plot(t, ADCGain, 'r-', label="Sample Frequency", linewidth=2)
p031, = ax03.plot(t, hr, 'b-', label="Heart Rate", linewidth=2)
p041, = ax04.plot(t, stepRate, 'b-', label="Step Rate", linewidth=2)
p051, = ax05.plot(t, pI, 'y-', label="Perfusion Index", linewidth=2)
p061, = ax06.plot(t, rawPPG, 'g-', label="Raw PPG", linewidth=2)
# set lagends
ax01.legend([p011, p021], [p011.get_label(), p021.get_label()], loc=2)
#ax02.legend([p021], [p021.get_label()])
ax03.legend([p031], [p031.get_label()], loc=2)
ax04.legend([p041], [p041.get_label()], loc=2)
ax05.legend([p051], [p051.get_label()], loc=2)
ax06.legend([p061], [p061.get_label()], loc=2)
# Data Update
xmin = 0.0
xmax = 50.0
x = 0.0
# create parser
parser = argparse.ArgumentParser(description="LDR serial")
# add expected arguments
parser.add_argument('--port', dest='port', required=True)
# parse args
args = parser.parse_args()
#strPort = '/dev/tty.usbserial-A7006Yqh'
strPort = args.port
print('reading from serial port %s...' % strPort)
# Handle serial
ser = serial.Serial(strPort, 9600)
print('plotting data...')
# Logfile writer
# open('test.csv','w') as csvfile
#logwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
# interval: draw new frame every 'interval' ms
# frames: number of frames to draw
simulation = animation.FuncAnimation(
f0, updateData, blit=False, frames=1000, interval=100, repeat=True)
# Uncomment the next line if you want to save the animation
# simulation.save(filename='sim.mp4',fps=1,dpi=300)
plt.show()
def updateData(self):
global x
global t
global ser
global hr
global HRQ
global Fs
global ADCGain
global stepRate
global pI
global rawPPG
try:
line = ser.readline().rstrip()
data = [float(val) for val in line.split()]
# print data
print(data)
if(len(data) == 9):
# log data
for i in range(len(data)):
out_string = ""
out_string += str(data[i])
# logwriter.writerow(out_string)
# update variables
tmpT = data[0]
tmpFs = data[1]
tmpStepRate = data[2]
tmpHr = data[3]
tmpPI = data[4]
tmpHRQ = data[5]
tmpRawPPG = data[6]
except KeyboardInterrupt:
print('exiting')
hr = append(hr, tmpHr)
HRQ = append(HRQ, tmpHRQ)
Fs = append(Fs, tmpFs)
stepRate = append(stepRate, tmpStepRate)
pI = append(pI, tmpPI)
rawPPG = append(rawPPG, tmpRawPPG)
t = append(t, x)
x += 1
p011.set_data(t, HRQ)
p021.set_data(t, Fs)
p031.set_data(t, hr)
p041.set_data(t, stepRate)
p051.set_data(t, pI)
p061.set_data(t, rawPPG)
if x >= xmax - 10.00:
p011.axes.set_xlim(x - xmax + 10.0, x + 10.0)
p021.axes.set_xlim(x - xmax + 10.0, x + 10.0)
p031.axes.set_xlim(x - xmax + 10.0, x + 10.0)
p041.axes.set_xlim(x - xmax + 10.0, x + 10.0)
p051.axes.set_xlim(x - xmax + 10.0, x + 10.0)
p061.axes.set_xlim(x - xmax + 10.0, x + 10.0)
return p011, p021, p031, p041, p051, p061
# Call main
if __name__ == '__main__':
main()
I use Python 3.43 and Matplotlib 1.5.0.
I created a small example:
# -*- coding: utf-8 -*-
import matplotlib
matplotlib.use("Qt5Agg")
matplotlib.use("Svg")
import matplotlib.pyplot as plt
txts = ['Bau', 'Landwirtschaft', 'Handel', 'Logistik', 'Handwerk', 'Gaststätten', 'Freiberufler', 'Dienstleistungen', 'Finanzanbieter', 'Handel', 'Einzelhandel', 'Vertrieb', 'Touristik', 'sonstige']
sizes = [104, 351, 1339, 456, 831, 661, 465, 323, 304, 294, 152, 133, 1006, 631]
ch_farben = ['#FF0000', '#0064EB', '#FFD700', '#00FF00', '#00CED1', '#006400', '#556B2F', '#87CEEB', '#DC143C', '#FFFACD', '#99FFCC', '#CD853F', '#20B2AA', '#C71585']
#Größe Picture in Inch
width_inch = 10.0
height_inch = 10.0
# Aulösung in dpi
dpis = 100
# Rand um Diagramm in Pixel
rand = 50
#Breite des Balkens >0 und <= 1
bar_width = 0.8
xpos = ()
lg_beschr = []
cnt_bars = len(sizes)
ymax =max(sizes)
smm = sum(sizes)
ymax = ymax
nc = cnt_bars // 10 + 1
for j in range(cnt_bars):
if smm != 0:
sprz = "%2.1f%%" % (100 * sizes[j]/smm)
if len(sprz) > 0:
lg_beschr.append(txts[j] + " (" + sprz + ")")
else:
lg_beschr.append(txts[j])
xpos = xpos + (j + (1 - bar_width)/2,)
br =cnt_bars
d = dict(left=xpos, width=bar_width, height= sizes, bottom=0, color=ch_farben)
sp111 =plt.subplot(111)
bars = sp111.bar(**d )
fig = plt.gcf()
fig.dpi = dpis
fig.set_figwidth(width_inch)
fig.set_figheight(height_inch)
rdx = rand / (width_inch * dpis)
rdy = rand / (height_inch * dpis)
fig.subplots_adjust(bottom=rdy, top=1.0-rdy, left=rdx, right=1.0-rdx)
sp111.set_position([0.05, 0.05, 0.72, 0.72])
ax = plt.gca()
chart_leg = ax.legend(bars, lg_beschr, loc='lower left', bbox_to_anchor=(0.0, 1.0), frameon= True, fontsize =14, ncol=nc, borderaxespad=0.1)
plt.draw()
#Speichern in svg-Dateien
plt.savefig("D:/TMP/test_diag.svg", format="svg", transparent=True, dpi=dpis)
plt.savefig("D:/TMP/test_diag.png", format="png", transparent=True, dpi=dpis)
plt.show()
plt.close()
All works fine, but if I have more values like 25..30 items, so the legend is bigger. I have to change the last two parameter for
sp111.set_position([0.05, 0.05, 0.72, 0.72])
manually to smaller values to get all of the legend. Is there a possibility to
automate this?
Is there a option to compute the size and location of the legend (in pixel, inch or axes coordinates)?
I am getting a very strange error using basemap. No error appears, yet my 3rd plot has no data plotted when data does indeed exist. Below is my code. When run, you will see that both modis and seawifs data is plotted, but viirs is not. I can't figure out why.
import numpy as np
import urllib
import urllib2
import netCDF4
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from datetime import datetime, date, time, timedelta
import json
import math
def indexsearch(datebroken,year, month, day):
for i in range(0,len(datebroken)):
if (datebroken[i,0] == year and datebroken[i,1] == month and datebroken[i,2] == day):
return i
url = 'http://coastwatch.pfeg.noaa.gov/erddap/griddap/erdMWchlamday.nc?chlorophyll' +\
'[(2002-07-16T12:00:00Z):1:(2015-04-16T00:00:00Z)][(0.0):1:(0.0)][(36):1:(39)][(235):1:(240)]'
file = 'erdMWchlamday.nc'
urllib.urlretrieve(url, file)
ncfilemod = netCDF4.Dataset(file)
ncv1 = ncfilemod.variables
print ncv1.keys()
time1=ncv1['time'][:]
inceptiondate = datetime(1970, 1, 1, 0, 0, 0)
timenew1=[]
for i in time1[:]:
newdate = inceptiondate + timedelta(seconds=i)
timenew1.append(newdate.strftime('%Y%m%d%H'))
datebroken1 = np.zeros((len(timenew1),4),dtype=int)
for i in range(0,len(timenew1)):
datebroken1[i,0] = int(timenew1[i][0:4])
datebroken1[i,1] = int(timenew1[i][4:6])
datebroken1[i,2] = int(timenew1[i][6:8])
datebroken1[i,3] = int(timenew1[i][8:10])
lon1= ncv1['longitude'][:]
lat1 = ncv1['latitude'][:]
lons1, lats1 = np.meshgrid(lon1,lat1)
chla1 = ncv1['chlorophyll'][:,0,:,:]
url = 'http://coastwatch.pfeg.noaa.gov/erddap/griddap/erdSWchlamday.nc?chlorophyll' +\
'[(1997-09-16):1:(2010-12-16T12:00:00Z)][(0.0):1:(0.0)][(36):1:(39)][(235):1:(240)]'
file = 'erdSWchlamday.nc'
urllib.urlretrieve(url, file)
#Ncfile 2
ncfilewif = netCDF4.Dataset(file)
ncv2 = ncfilewif.variables
print ncv2.keys()
time2=ncv2['time'][:]
inceptiondate = datetime(1970, 1, 1, 0, 0, 0)
timenew2=[]
for i in time2[:]:
newdate = inceptiondate + timedelta(seconds=i)
timenew2.append(newdate.strftime('%Y%m%d%H'))
datebroken2 = np.zeros((len(timenew2),4),dtype=int)
for i in range(0,len(timenew2)):
datebroken2[i,0] = int(timenew2[i][0:4])
datebroken2[i,1] = int(timenew2[i][4:6])
datebroken2[i,2] = int(timenew2[i][6:8])
datebroken2[i,3] = int(timenew2[i][8:10])
lon2= ncv2['longitude'][:]
lat2 = ncv2['latitude'][:]
lons2, lats2 = np.meshgrid(lon2,lat2)
chla2 = ncv2['chlorophyll'][:,0,:,:]
url = 'http://coastwatch.pfeg.noaa.gov/erddap/griddap/erdVH2chlamday.nc?chla' +\
'[(2012-01-15):1:(2015-05-15T00:00:00Z)][(39):1:(36)][(-125):1:(-120)]'
file = 'erdVH2chlamday.nc'
urllib.urlretrieve(url, file)
ncfileviir = netCDF4.Dataset(file)
ncv3 = ncfileviir.variables
print ncv3.keys()
time3=ncv3['time'][:]
inceptiondate = datetime(1970, 1, 1, 0, 0, 0)
timenew3=[]
for i in time3[:]:
newdate = inceptiondate + timedelta(seconds=i)
timenew3.append(newdate.strftime('%Y%m%d%H'))
datebroken3 = np.zeros((len(timenew3),4),dtype=int)
for i in range(0,len(timenew3)):
datebroken3[i,0] = int(timenew3[i][0:4])
datebroken3[i,1] = int(timenew3[i][4:6])
datebroken3[i,2] = int(timenew3[i][6:8])
datebroken3[i,3] = int(timenew3[i][8:10])
lon3= ncv3['longitude'][:]
lat3 = ncv3['latitude'][:]
lons3, lats3 = np.meshgrid(lon3,lat3)
chla3 = ncv3['chla'][:,:,:]
i1=indexsearch(datebroken1,2012,6,16)
print i1
i2=indexsearch(datebroken2,2010,6,16)
print i2
i3=indexsearch(datebroken3,2012,6,15)
print i3
chla1plot = chla1[i1,:,:]
chla2plot = chla2[i2,:,:]
chla3plot = chla3[i3,:,:]
ncfileviir.close()
ncfilemod.close()
ncfilewif.close()
Important code is below here. All code above is just pulling the data into python to plot.
minlat = 36
maxlat = 39
minlon = 235
maxlon = 240
# Create map
fig = plt.figure()
#####################################################################################################################
#plot figure 1
ax1 = fig.add_subplot(221)
m = Basemap(projection='merc', llcrnrlat=minlat,urcrnrlat=maxlat,llcrnrlon=minlon, urcrnrlon=maxlon,resolution='h')
cs1 = m.pcolormesh(lons1,lats1,chla1plot,cmap=plt.cm.jet,latlon=True)
m.drawcoastlines()
m.drawmapboundary()
m.fillcontinents()
m.drawcountries()
m.drawstates()
m.drawrivers()
#Sets up parallels and meridians.
parallels = np.arange(36.,39,1.)
# labels = [left,right,top,bottom]
m.drawparallels(parallels,labels=[False,True,True,False])
meridians = np.arange(235.,240.,1.)
m.drawmeridians(meridians,labels=[True,False,False,True])
ax1.set_title('Modis')
#####################################################################################################################
#plot figure 2
ax2 = fig.add_subplot(222)
cs2 = m.pcolormesh(lons2,lats2,chla2plot,cmap=plt.cm.jet,latlon=True)
m.drawcoastlines()
m.drawmapboundary()
m.fillcontinents()
m.drawcountries()
m.drawstates()
m.drawrivers()
#Sets up parallels and meridians.
parallels = np.arange(36.,39,1.)
# labels = [left,right,top,bottom]
m.drawparallels(parallels,labels=[False,True,True,False])
meridians = np.arange(235.,240.,1.)
m.drawmeridians(meridians,labels=[True,False,False,True])
ax2.set_title('SeaWIFS')
#####################################################################################################################
#plot figure 3
ax3 = fig.add_subplot(223)
cs3 = m.pcolormesh(lons3,np.flipud(lats3),np.flipud(chla3plot),cmap=plt.cm.jet,latlon=True)
m.drawcoastlines()
m.drawmapboundary()
m.fillcontinents()
m.drawcountries()
m.drawstates()
m.drawrivers()
#Sets up parallels and meridians.
parallels = np.arange(36.,39,1.)
# labels = [left,right,top,bottom]
m.drawparallels(parallels,labels=[False,True,True,False])
meridians = np.arange(235.,240.,1.)
m.drawmeridians(meridians,labels=[True,False,False,True])
ax3.set_title('VIIRS')
# Save figure (without 'white' borders)
#plt.savefig('SSTtest.png', bbox_inches='tight')
plt.show()
My results are shown here!
![results]: http://i.stack.imgur.com/dRjkU.png
The issue that I found was that I had
minlat = 36
maxlat = 39
minlon = 235
maxlon = 240
m = Basemap(projection='merc', llcrnrlat=minlat,urcrnrlat=maxlat,llcrnrlon=minlon, urcrnrlon=maxlon,resolution='h')
The final plot was -125 to -120 which basemap did not automatically handle, but instead placed the plot at an area where I did not have data. I added a new m = basemap statement and changed the meridian numbers for the third graph using -125 to -120 as my longitude and the graph plotted just fine.