def test_hodograph_wind_vectors(): """Test plotting wind vectors onto a hodograph.""" u_wind = np.array([-10, -7, 0, 7, 10, 7, 0, -7]) v_wind = np.array([0, 7, 10, 7, 0, -7, -10, -7]) fig = plt.figure(figsize=(6, 6)) ax = fig.add_subplot(1, 1, 1) h = Hodograph(ax, component_range=20) h.plot(u_wind, v_wind, linewidth=3) h.wind_vectors(u_wind, v_wind) return fig
def test_hodograph_units(): """Test passing unit-ed quantities to Hodograph.""" fig = plt.figure(figsize=(9, 9)) ax = fig.add_subplot(1, 1, 1) hodo = Hodograph(ax) u = np.arange(10) * units.kt v = np.arange(10) * units.kt hodo.plot(u, v) hodo.plot_colormapped(u, v, np.sqrt(u * u + v * v), cmap='Greys') return fig
def test_hodograph_api(): """Basic test of Hodograph API.""" fig = plt.figure(figsize=(9, 9)) ax = fig.add_subplot(1, 1, 1) hodo = Hodograph(ax, component_range=60) hodo.add_grid(increment=5, color='k') hodo.plot([1, 10], [1, 10], color='red') hodo.plot_colormapped(np.array([1, 3, 5, 10]), np.array([2, 4, 6, 11]), np.array([0.1, 0.3, 0.5, 0.9]), cmap='Greys') return fig
fig = plt.figure(figsize=(9, 9)) add_metpy_logo(fig, 630, 80, size='large') # Grid for plots gs = gridspec.GridSpec(3, 3) skew = SkewT(fig, rotation=45, subplot=gs[:, :2]) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(p, T, 'r') skew.plot(p, Td, 'g') skew.plot_barbs(p, u, v) skew.ax.set_ylim(1000, 100) # Add the relevant special lines skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() # Good bounds for aspect ratio skew.ax.set_xlim(-30, 40) # Create a hodograph ax = fig.add_subplot(gs[0, -1]) h = Hodograph(ax, component_range=60.) h.add_grid(increment=20) h.plot(u, v) # Show the plot plt.show()
# Grid for plots gs = gridspec.GridSpec(3, 3) skew = SkewT(fig, rotation=45, subplot=gs[:, :2]) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(pressure, temperature, 'r') skew.plot(pressure, dewpoint, 'g') skew.plot_barbs(pressure, u_wind, v_wind) skew.ax.set_ylim(1000, 100) # Add the relevant special lines skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() # Good bounds for aspect ratio skew.ax.set_xlim(-40, 60) # Create a hodograph ax = fig.add_subplot(gs[0, -1]) h = Hodograph(ax, component_range=60.) h.add_grid(increment=20) h.plot(u_wind, v_wind) # Add a title skew.ax.set_title(station + ' ' + date.strftime("%d %b %Y %HZ")) # Show the plot plt.show()
pressure = df['pressure'].values * units(df.units['pressure']) temperature = df['temperature'].values * units(df.units['temperature']) wind_speed = df['speed'].values * units.knots print(temperature) dewpoint = df['dewpoint'].values * units(df.units['dewpoint']) print(dewpoint) u_wind = df['u_wind'].values * units(df.units['u_wind']) print(u_wind) v_wind = df['v_wind'].values * units(df.units['v_wind']) heights = df['height'].values * units(df.units['height']) print(mpcalc.wind_direction(u_wind,v_wind)) fig = plt.figure(figsize=(6,6)) ax = fig.add_subplot(1,1,1) h= Hodograph(ax,component_range=60.) h.plot(u_wind,v_wind,linewidth=5) h.add_grid(increment=10) #h.add_grid(increment=20,color='tab:orange',linestyle='-') h.plot_colormapped(u_wind, v_wind, wind_speed) # Plot a line colored by wind speed plt.savefig('hodograph.png') plt.show() sys.exit() #lcl_pressure, lcl_temperature = mpcalc.lcl(pressure[0], temperature[0], dewpoint[0]) #print(lcl_pressure, lcl_temperature) # Calculate the parcel profile. parcel_prof = mpcalc.parcel_profile(pressure, temperature[0], dewpoint[0]).to('degC')
# Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=(9, 9)) # Grid for plots gs = gridspec.GridSpec(3, 3) skew = SkewT(fig, rotation=45, subplot=gs[:, :2]) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot skew.plot(p, T, 'r') skew.plot(p, Td, 'g') skew.plot_barbs(p, u, v) skew.ax.set_ylim(1000, 100) # Add the relevant special lines skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() # Good bounds for aspect ratio skew.ax.set_xlim(-30, 40) # Create a hodograph ax = fig.add_subplot(gs[0, -1]) h = Hodograph(ax, component_range=60.) h.add_grid(increment=20) h.plot(u, v) # Show the plot plt.show()
def plot_skewt(snd: Sounding, save_to: Optional[str] = None, p_top: int = 100): """ Plots a skew-T from the given Sounding. :param snd: The Sounding. :param save_to: Where to save the figure. Default None, which does not save the figure, and instead shows it. :param p_top: Pressure at the top of the skew-T. If you change this, Metpy might change the rotation of the isotherms. No known fix yet. :return: None. """ #################################################################################################################### # Data extraction and masking # Extract data from sounding. p = snd.p T = snd.T Td = snd.Td Tw = snd.Tw Te = snd.thetaE z = snd.z cf = snd["CFRL"] omega = snd.omega u, v = snd.wind_components() e = mpcalc.saturation_vapor_pressure(T) rv = mpcalc.mixing_ratio(e, p) w = mpcalc.vertical_velocity(omega, p, T, rv).to("cm/s") # Create masks to filter what data is plotted. mask_dewpoint = Td > -9000. * units.degC # Plot only non-missing dewpoints. mask_wetbulb = Tw > -9000. * units.degC # Plot only non-missing dewpoints. mask_thetae = Te > 0. * units.K # Plot only non-missing theta-es. mask_barbs = p > p_top * units.hPa # Plot only winds below the top of the sounding. #################################################################################################################### # Define intervals of height for coloring barbs and hodograph. z_interval_levels = [1500, 3000, 6000, 9000, 12000, 99999] z_interval_colors = ["red", "orange", "green", "blue", "purple", "grey"] z_colors = [] for item in z: for color, interval in zip(z_interval_colors, z_interval_levels): if item <= interval * units.meter: z_colors.append(color) break #################################################################################################################### # Plotting skew-T fig = plt.figure(figsize=(11, 11)) ax_hodo = fig.add_axes([0.70, 0.675, 0.25, 0.25]) ax_thte = fig.add_axes([0.70, 0.375, 0.25, 0.25]) skew = SkewT(fig, rotation=45, rect=[0.05, 0.05, 0.60, 0.9]) # Plot temperature, dewpoint, and wet-bulb. skew.plot(p, T, 'r') skew.plot(p[mask_dewpoint], Td[mask_dewpoint], 'g') skew.plot(p[mask_wetbulb], Tw[mask_wetbulb], color='#009999', linewidth=1) # Calculate and plot surface parcel trace. sfc_trace = snd.parcel_trace(0).to('degC') sfc_trace_plot = skew.plot(p, sfc_trace, c='orange', linewidth=2, zorder=-10) # Calculate and plot MU parcel trace. mu_level_index = np.argmax(Te[p > 750. * units.hPa]) mu_trace = snd.parcel_trace(mu_level_index).to('degC') mu_trace_plot = skew.plot(p[mu_level_index:], mu_trace, c='gray', linewidth=2, zorder=-9) # Plot each barb individually for control over color. Unfortunately, the c arg of plot_barbs doesn't work for this # purpose. for p_, u_, v_, c_ in zip(p[mask_barbs][::BARB_DENSITY], u[mask_barbs][::BARB_DENSITY], v[mask_barbs][::BARB_DENSITY], np.array(z_colors)[mask_barbs][::BARB_DENSITY]): skew.plot_barbs(p_, u_, v_, y_clip_radius=0.03, barbcolor=c_) #################################################################################################################### # Cloud fraction and omega zero_line = 1 / 15 cf_plot = (cf * zero_line) / 100 w_plot = (w.magnitude / 20) + zero_line skew.ax.plot(np.zeros(cf_plot.shape) + 1 / 15, snd.p, transform=skew.ax.get_yaxis_transform(), color="grey") skew.ax.plot(cf_plot, snd.p, transform=skew.ax.get_yaxis_transform(), color="black") skew.ax.plot(w_plot, snd.p, transform=skew.ax.get_yaxis_transform(), color="purple") skew.ax.text(np.max(w_plot), snd.p[np.argmax(w_plot)], " {:.1f}".format(np.max(w.magnitude)), color="purple", ha="left", va="center", transform=skew.ax.get_yaxis_transform()) skew.ax.text(max(np.min(w_plot), 0), snd.p[np.argmin(w_plot)], " {:.1f}".format(np.min(w.magnitude)), color="purple", ha="left", va="center", transform=skew.ax.get_yaxis_transform()) # skew.ax.fill_betweenx(snd.p, cloud_fractions, np.zeros(cloud_fractions.shape)) #################################################################################################################### # Tweaking skew.ax.set_xlim(-30, 40) skew.ax.set_ylim(1020, p_top) skew.ax.set_xlabel("") skew.ax.set_ylabel("") # Add legend for the parcel traces. skew.ax.legend(handles=[ mlines.Line2D([], [], color='orange', label='Surface parcel'), mlines.Line2D([], [], color='gray', label=r"Max $\theta_e$ below 750mb"), mlines.Line2D([], [], color='black', label=r"Cloud fraction"), mlines.Line2D([], [], color='purple', label=r"Vertical velocity (cm/s)"), ], loc="upper center") # Add adiabats and isohumes. skew.plot_dry_adiabats(t0=np.arange(233, 533, 10) * units.K, alpha=0.25, color='orangered') skew.plot_moist_adiabats(t0=np.arange(233, 400, 5) * units.K, alpha=0.25, color='tab:green') # Reshape required as a quirk of metpy. skew.plot_mixing_lines(w=np.array( [1, 2, 3, 4, 6, 8, 10, 12, 16, 20, 24, 28, 36]).reshape(-1, 1) / 1000., p=np.arange(1000, 99, -100) * units.hPa, linestyle='dotted', color='tab:blue') plt.title('RAP sounding at {}'.format(snd.params["STID"]), loc='left') plt.title('{:.0f}-hour forecast valid at {}'.format( snd.params["STIM"], snd.params["TIME"]), loc='right') #################################################################################################################### # Theta-E plot # Set up axis for theta-e plot. ax_thte.plot(Te[mask_thetae], p[mask_thetae]) ax_thte.set_xlim(300, 360) ax_thte.set_ylim(1020, p_top) ax_thte.set_yscale("log") ax_thte.set_yticks(np.arange(p_top, 1001, 100)) ax_thte.set_yticklabels(np.arange(p_top, 1001, 100)) ax_thte.set_xlabel("") ax_thte.grid(axis="both") plt.text(0.5, 0.9, "Theta-E (Kelvins)", ha="center", va="center", transform=ax_thte.transAxes) #################################################################################################################### # Hodograph # Set up axis for hodograph. h = Hodograph(ax_hodo, component_range=100) h.add_grid(20) # Plot each segment individually for control over color, reversed so that the full hodograph is plotted first, # followed by all but the last segment, etc. Unfortunately, the plot_colormapped() function doesn't work for this # purpose. for color, interval in zip(reversed(z_interval_colors), reversed(z_interval_levels)): mask = z < interval * units.meter h.plot(u.magnitude[mask], v.magnitude[mask], c=color) for vector in snd.bunkers_storm_motion(): h.plot(vector[0], vector[1], c="black", markersize=3, marker="o") ax_hodo.set_xticks([]) ax_hodo.set_yticks([]) ax_hodo.set_xlim(-60, 100) ax_hodo.set_ylim(-60, 100) plt.text(0.1, 0.9, "Velocity (knots)", ha="left", va="center", transform=ax_hodo.transAxes) for a in range(20, 61, 20): ax_hodo.text(-a * 0.71, -a * 0.71, a, ha="center", va="center") ######################################################################################################################## parameter_names = ["SB STP", "0-1 SRH", "SB CAPE", "SB CIN"] parameters = [ snd.significant_tornado()[0], snd.storm_relative_helicity()[2], snd.cape_cin(0)[0], snd.cape_cin(0)[1] ] for name, value, i in zip(parameter_names, parameters, range(len(parameters))): s = "{:15} {:10.3f}".format(name, value.magnitude) fig.text(0.70, 0.32 - (0.02 * i), s, ha="left", va="top", family="monospace", transform=fig.transFigure) ######################################################################################################################## if save_to is None: plt.show() else: plt.savefig(save_to) plt.close()
# Shade areas of CAPE and CIN skew.shade_cin(p, T, parcel_prof, Td) skew.shade_cape(p, T, parcel_prof) # Plot a zero degree isotherm skew.ax.axvline(0, color='c', linestyle='--', linewidth=3) # Add the relevant special lines skew.plot_dry_adiabats(linewidth=2.5) skew.plot_moist_adiabats(linewidth=2.5) skew.plot_mixing_lines(linewidth=2.5) ax1 = fig.add_subplot(gs[0:7, 4]) h = Hodograph(ax1, component_range=50.) h.add_grid(increment=12.5) h.plot(u, v, color='#0080ff') ax1.tick_params(labelsize=15.) ax1.set_xticks(np.arange(-50., 75., 25.)) ax1.set_yticks(np.arange(-50., 75., 25.)) ax1.set_xticklabels([]) ax1.set_title('Hodograph', fontsize=20.) ax1.set_xlabel('wind speed ($m$ $s^{-1}$)', fontsize=15.) ax1.set_ylabel('wind speed ($m$ $s^{-1}$)', fontsize=15.) ax2 = fig.add_subplot(gs[9:15, 4]) [ax2.add_patch(PolygonPatch(shape, fc='none')) for shape in shapes] ax2.scatter(lon[10:], lat[10:], c='r', s=10) ax2.tick_params(labelsize=15.) ax2.set_xticks(np.arange(119.5, 122., 0.5)) ax2.set_yticks(np.arange(22., 24.5, 0.5)) ax2.set_xticklabels(['', '120°E', '', '121°E', ''])
ax2.yaxis.tick_left() ax2.tick_params(direction='in', pad=-5) #PLOT PARCEL STUFF plt.plot((37, 43), (mupcl.lfcpres,mupcl.lfcpres), 'r-',lw=1.5) ax2.annotate('LFC', xy=(40, mupcl.lfcpres-10), xytext=(40, mupcl.lfcpres-10),ha='center', color='r') plt.plot((37, 43), (mupcl.lclpres,mupcl.lclpres), 'g-',lw=1.5) ax2.annotate('LCL', xy=(40, mupcl.lclpres+50), xytext=(40, mupcl.lclpres+50),ha='center', color='g') # Create windbarbs and hodograph skew.plot_barbs(p, u, v, xloc=1.1) hgt_list = [0,3000,6000,9000,np.max(h)] hodo_color = ['r','g','y','c'] hodo_label = ['0-3km','3-6km','6-9km','>9km'] ax_hod = inset_axes(skew.ax, '40%', '40%', loc=1) for tick in ax_hod.xaxis.get_major_ticks(): tick.label.set_fontsize(10) tick.label.set_rotation(45) for tick in ax_hod.yaxis.get_major_ticks(): tick.label.set_fontsize(10) hodo = Hodograph(ax_hod, component_range=80.) hodo.add_grid(increment=20) for k in range(len(hgt_list)-1): index1 = min(range(len(h)), key=lambda i: abs(h[i]-hgt_list[k])) index2 = min(range(len(h)), key=lambda i: abs(h[i]-hgt_list[k+1])) hodo.plot(u[index1:index2+1],v[index1:index2+1],c=hodo_color[k],linewidth=2.0,label=hodo_label[k]) ax_hod.legend(loc=2,prop={'size':8}) plt.savefig('/home/kgoebber/http/soundings/launches/'+launch+'_'+ascent+'/'+launch+'_'+ascent+'_KVUM.png',dpi=150) #plt.show()
#cambiando la direccion cardinal a angular angle = np.zeros(len(direction) + 2) #añado el dos para igualar size de ambas columnas #corregir #cambiar la denominacion: NS por NW for i in range(2, len(direction) + 2): angle[i] = portolan.middle(direction.direccion[i]) #5. GENERACIÓN DE LA HODOGRAFA angle = pd.DataFrame(angle[2:], columns=['angulo']) wind_speed = wind.values * units.knots wind_dir = angle.values * units.degrees u, v = mpcalc.wind_components(wind_speed, wind_dir) #visualizando la hodografa fig = plt.figure(figsize=(6, 6)) fig.suptitle('Hodografa - Estacion 000527') ax = fig.add_subplot(1, 1, 1) h = Hodograph(ax, component_range=10.) h.plot(u, v, linewidth=5) h.add_grid(increment=5) plt.savefig(dir_file + '/hodografa.png') #resultado: dado que la hodografa es casi constante en todo la figura #concluimos que la velocidad del viento es casi constante en modulo y direccion