def windrose_data(wind_direction, wind_speed, figure): """ Creates a windrose plot Arguments --------- wind_direction: list wind direction time series wind_speed: list wind speed time series figure: matplotlib.figure.Figure figure on which windrose is plotted Returns ------- message: str The nicely formatted message. """ ax = WindroseAxes.from_ax(fig=figure) ax.bar(wind_direction, wind_speed, normed=True, opening=1, edgecolor='white', nsector=8) ax.set_legend(loc="best", prop={'size': 5}) return ax
def windrose(): from windrose import plot_windrose, WindroseAxes import matplotlib.cm as cm set_windrose_style() ws = df['Wspd.m/s'].ffill() wd = df['Wdir.deg'].ffill() conc = df['GEM_avg_conc'].ffill() dfW = pd.DataFrame({'speed': ws, 'direction': wd, 'conc': conc}) plot_windrose(dfW, kind='contourf', bins=np.arange(0.01, 8, 1), cmap=cm.hot, lw=3) ax = WindroseAxes.from_ax() ax.bar(dfW.direction, dfW.conc, normed=True, opening=0.8, edgecolor='white') ax.set_legend() plot_windrose(dfW, kind='contourf', var_name='conc', direction_name='direction', bins=np.arange(0.01, dfW.conc.max(), 0.2))
def wind_rose_plot(ws, wd): both_not_nan_mask = np.bitwise_and(~np.isnan(ws), ~np.isnan(wd)) ws, wd = ws[both_not_nan_mask], wd[both_not_nan_mask] ax = WindroseAxes.from_ax( theta_labels=["E", "N-E", "N", "N-W", "W", "S-W", "S", "S-E"]) ax.bar(wd, ws, normed=True, opening=0.95, edgecolor='white') ax.set_legend(loc='best')
def draw_one_attribute_windrose(shp_file,field_name,attribute, output,color='grey',hatch=""): """ draw the figure of one attribute's wind rose Args: shp_file: shape file path attribute_name: name of attribute output: output the figure Returns: True if successful, False otherwise """ values = read_attribute(shp_file,field_name) from windrose import WindroseAxes wind_dir = np.array(values) wind_sd = np.ones(wind_dir.shape[0]) #np.ones(wind_dir.shape[0]) #np.arange(1, wind_dir.shape[0] + 1) bins_range = np.arange(1, 2, 1) # this sets the legend scale ax = WindroseAxes.from_ax() ax.bar(wind_dir, wind_sd, normed=True, bins=bins_range,colors=color) ax.set_yticks(np.arange(5, 16, step=5)) ax.set_yticklabels(np.arange(5, 16, step=5)) # plt.show() plt.savefig(output) # plt.grid(True) # plt.savefig(output) # basic.outputlogMessage("Output figures to %s"%os.path.abspath(output)) # basic.outputlogMessage("ncount: " + str(n)) # basic.outputlogMessage("bins: "+ str(bins)) return True
def windrose(wd, ws, title, fig2, **kwargs): model = kwargs.pop('model', True) fig2.canvas.set_window_title(title) # Shift wind directions if model: wd[np.where(wd > 360)] = wd[np.where(wd > 360)] - 360 ax21 = WindroseAxes.from_ax(fig=fig2) ax21.bar(wd, ws, bins=np.arange(-0.05, 14, 2), normed=True, opening=0.8, edgecolor='white', cmap=plt.cm.viridis) ax21.set_legend() ax21.set_title("%s" % (title[:title.find('_')]), y=0.98, x=0., size='xx-large') if model: ax21.text(0.05, 0.95, "%s" % ('model'), size='x-large', transform=ax21.transAxes) else: ax21.text(0.05, 0.95, "%s" % ('observation'), size='x-large', transform=ax21.transAxes)
def plot_wind_rose_at_cities(self,datatype=['UINT','VINT']): """ plot wind rose at each city based on cities['city']['UINT'] and ['VINT']""" from windrose import WindroseAxes from matplotlib import pyplot as plt import matplotlib.cm as cm import numpy as np #fig, ax = plt.subplots(5,2,sharex=True) #plt_idx=0 for city,var in self.cities.iteritems(): # convert all the u and v into one array u_int=np.concatenate([ var[datatype[0]][i] for i,b in var[datatype[0]].iteritems()]) v_int=np.concatenate([ var[datatype[1]][i] for i,b in var[datatype[1]].iteritems()]) # http://stackoverflow.com/questions/21484558/how-to-calculate-wind-direction-from-u-and-v-wind-components-in-r # get from u v to windrose wind_abs=np.sqrt(np.power(u_int,2.0)+np.power(v_int,2.0)) wind_dir_trig_to = np.arctan2(u_int/wind_abs,v_int/wind_abs) wind_dir_trig_to_degrees = wind_dir_trig_to * 180.0/np.pi wind_dir_trig_from_degrees = wind_dir_trig_to_degrees + 180.0 wind_dir_cardinal = 90 - wind_dir_trig_from_degrees # draw wind rose ax = WindroseAxes.from_ax() ax.bar(wind_dir_trig_from_degrees, wind_abs, normed=True, opening=0.8, edgecolor='white') #ax.bar(wind_dir_cardinal, wind_abs, normed=True, opening=0.8, edgecolor='white') ax.set_legend() ax.set_title(city) #plt_idx+=1 #plt.show(block=False) #savefig('foo.png') fname='windrose_'+datatype[0]+datatype[1]+'_'+city+'.png' plt.savefig(fname,format='png',dpi=300)
def plot_windrose(df, letter=None, title=False): date = str(df.index[0].date()) windf = df.drop(df[(df.ws == 0) & (df.wd == 0)].index) # Necessary to plot pies instead of triangles # see: https://github.com/python-windrose/windrose/issues/43 plt.hist([0, 1]) plt.close() fig = plt.figure(figsize=(14, 9)) fig.text(0.2, 0.95, letter, fontsize=24, style='italic') ax = WindroseAxes.from_ax(fig=fig) if title: ax.set_title(date) ax.bar(windf['wd'], windf['ws'], normed=True, opening=0.8, edgecolor='black', bins=np.arange(0, 8, 1)) ax.set_yticks(np.arange(10, 60, step=10)) ax.set_yticklabels(np.arange(10, 60, step=10)) ax.yaxis.set_major_formatter(StrMethodFormatter(u"{x:.0f}%")) ax.legend(loc='center left', bbox_to_anchor=(1.05, 0.5), title='Wind speed (m/s)') plt.savefig(f"{make_dir('Results/Plots/Lapup/')}{date}{letter[0]}.png")
def plot_windrose(data): # Wind properties vento_dir = data['vento_dir'].to_numpy() vento_rajmax = data['vento_rajmax'].to_numpy() vento_vel = data['vento_vel'].to_numpy() # Correction vento_dir = (vento_dir + 90) % 360 ax = WindroseAxes.from_ax() ax.bar(vento_dir, vento_vel, normed=True, opening=0.8, edgecolor='white', cmap=cm.jet) ax.set_xticklabels(['N', 'NW', 'W', 'SW', 'S', 'SE', 'E', 'NE']) # Change if necessary ax.set_legend(title="Wind speed (m/s)", bbox_to_anchor=(-0.05, -0.11), ncol=6) ax.set_theta_zero_location('N') path = './tmp/windrose.png' plt.savefig(path, dpi=250) plt.close() return path
def wind_rose(Angle, Intensity, place=None, fig=None, legend=False, coord=False, **kwargs): #### Angle : Orientation of the wind #### Intensity : Intensity of tje wind #### Nbin : nbins in terms of velocity #### Nsector : n bins in terms of direction Angle = np.array(Angle) Intensity = np.array(Intensity) ## removing nans inds = ~np.logical_or(np.isnan(Angle), np.isnan(Intensity)) Angle = Angle[inds] Intensity = Intensity[inds] ####### documentation https://windrose.readthedocs.io/en/latest/ ax = WindroseAxes.from_ax(fig=fig) if place != None: ax.set_position(place, which='both') # bars = ax.bar(Angle, Intensity, normed=True, opening=1, edgecolor='k', nsector = Nsector, bins = Nbin, cmap = cmap) Angle = (90 - Angle) % 360 bars = ax.bar(Angle, Intensity, **kwargs, zorder=20) ax.set_axisbelow(True) if legend: ax.set_legend() if not coord: ax.set_xticklabels([]) ax.set_yticklabels([]) return ax
def plot_speed_range(measure_data, vmin, vmax, duration, show=False): ''' Filter data by wind speed between vmin (included) and vmax (not included) INPUT duration: the mesured duration [min] ''' df = measure_data.loc[(vmin <= measure_data.loc[:, "speed"]) & (measure_data.loc[:, "speed"] < vmax)] ax = WindroseAxes.from_ax() ax.bar(df.direction, df.speed, normed=False, nsector=36) wd_count = np.sum(ax._info['table'], axis=0) # cumulative appearance in each # direction wd_time = wd_count * duration # plot result by bar if show: axis = plt.subplot() axis.bar(np.arange(0, 360, 10), wd_time, width=8) axis.grid(axis='y') axis.set_xlabel("Wind direction (°)") axis.set_ylabel("Time (min)") axis.set_xticks(np.arange(0, 360, 10)) axis.set_title("Wind directions at mean speed {} m/s".format( (vmin + vmax) / 2.0)) plt.show() res = pandas.DataFrame(wd_time, index=range(0, 360, 10), columns=["Time"]) return res
def plotcontourfWindrose(filename, location, cmap=cm.hot, bin_interval=10): """ Plotting function to generate windrose bar diagram for provided wind speed / directional data. Usage: 'filename': type = str; location of .csv data file. 'location': type = str; location where data was collected. 'bins': type = np.array; np.arange(minspeed, maxspeed, bin_interval), e.g. np.array(0.001, 100, 10). 'cmap': type = matplotlib.cm option; e.g. cmap=cm.hot. """ df = pd.read_csv(filename, header=1, low_memory=False) df.rename(columns={ 'Wind Dir (10s deg)': 'direction(10sdeg)', 'Wind Spd (km/h)': 'speed', 'Wind Dir Flag': 'direction_flag', 'Wind Spd Flag': 'speed_flag' }, inplace=True) df['direction'] = 10 * df['direction(10sdeg)'] bins = np.arange(df['speed'].min(), df['speed'].max(), bin_interval) ax = WindroseAxes.from_ax() ax.contourf(df.direction.values, df.speed.values, bins=bins, cmap=cmap) ax.set_title('Wind Polar Plot: {}'.format(location), fontsize=16) ax.set_legend(ncol=2, title='Wind Speed (km/h)') plt.savefig('contourf.pdf') plt.show() return None
def Wind_Rose_Map(ws, wd, ax=None): import matplotlib.cm as cm # Create wind speed and direction variables if ax is None: ax = WindroseAxes.from_ax() ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='black') ax.set_legend() return ax
def plotWindRose(dir, wind, windfarm, turbine, pgeo, tini, tend): ax = WindroseAxes.from_ax() ax.bar(dir, wind, normed=True, opening=0.8, edgecolor='white') ax.set_legend() plt.title(windfarm[0] + ' ' + '#' + turbine[0] + '{:12.6f}'.format(pgeo[0]) + ' ' + '{:12.6f}'.format(pgeo[1]) + '\n' + 'Start: ' + str(tini) + ' End: ' + str(tend)) return
def windrosecontour(ws, wd): from windrose import WindroseAxes from matplotlib import pyplot as plt import matplotlib.cm as cm ax = WindroseAxes.from_ax() ax.contourf(wd, ws, bins=np.arange(0, 8, 1), cmap=cm.hot) ax.contour(wd, ws, bins=np.arange(0, 8, 1), colors='black') ax.set_legend() plt.show()
def plot_data_of_one_item(var, dir_a, item, ang=40, rmax=None, bins=None, N=None, unit=None, title=None, fontsize=None, per=None): # var 为所描述数值 # bins 为单个条目的概率区分数列,np.linspace(...),传入整数时默认为分级个数,默认为5 # N为方向的区分度,有几圈,默认为5 # ang 为标注各圈概率值的标签所在数轴角度 # unit 为所分布值的单位 # rmax 为最大概率值,即最外圈所表示的百分比 bins = bins[:-1] fig = plt.figure(figsize=(16, 9), dpi=200) ax = WindroseAxes.from_ax(fig=fig, rmax=rmax) ax.bar(dir_a, var, normed=True, opening=0.8, edgecolor='white', bins=bins, N=N, cmap=cm.rainbow) # ax.box(dir, var, normed=True, edgecolor='white', bins=bins, cmap=cm.rainbow) ax.set_legend(title=item + unit, fancybox=False, facecolor='ivory', edgecolor='black', ncol=bins // 5 if isinstance(bins, int) else len(bins) // 5, fontsize=15, bbox_to_anchor=(0, 0)) ax.set_radii_angle(angle=45 if not ang else ang) ax.tick_params(axis='y', direction='inout', colors='darkblue', pad=1) ax.tick_params(axis='x', colors='black', labelsize=15, pad=2) ax.grid(color='black', linestyle=':', linewidth=1, alpha=1) ax.set_rorigin(-rmax / 11) ax.text(.5, .5, "缺测\n数据\n" + str(round(100 - float(per), 2)) + "%", horizontalalignment='center', verticalalignment='center', transform=ax.transAxes) title = item + " " + title if title else item ax.set_title(title + "(有效数据:" + per[:5] + "%)", {'fontsize': 20 if not fontsize else fontsize}) fig_file = title + '.png' fig.savefig(fig_file.replace(r'/', '_'), dpi=200, bbox_inches='tight') logging.info(fig_file.replace(r'/', '_') + '保存成功') plt.close()
def plot_windrose(ws,wd,diro,file_Merge): '''画风向玫瑰图''' ####wind frequence rose################################################ numbins = [0, 5, 10, 15, 20, 25] ax = WindroseAxes.from_ax(fig = plt.figure(figsize=(5,5))) ax.set_title(file_Merge[6:10]+'_'+ws.name[3:]+'风向') ax.bar(wd, ws, bins=numbins, normed=True,nsector=16,opening=0.8, edgecolor='white') set_legend(ax) plt.savefig(diro+'\\'+file_Merge[6:10]+'_'+ws.name[3:]+'Windrose.png') plt.show()
def plot_wind_rose_we_mb(ws,wd,diro,file_Merge,density): """做风能玫瑰图""" density = density we = ws**3*density*0.5 ax = WindroseAxes.from_ax(fig = plt.figure(figsize=(5,5))) numbins = [0, 200, 400, 600, 800, 1000] ax.bar(wd, we, bins=numbins, normed=True, \ opening=0.8, edgecolor='white', we='windenergy') ax.set_legend() ax.set_title(file_Merge[6:10]+'_'+ws.name[3:]+'风能') plt.savefig(diro+'\\'+file_Merge[6:10]+'_'+ws.name[3:]+'Windenergy.png',bbox_inches='tight',dpi=96)
def windRouse(self, archvo): # creamos datos de direcion y velocidad ws = np.random.random(500) * 10 print(len(ws), " ", ws) wd = np.random.random(500) * 360 # [x*30 for x in range(0,12)] print(len(wd), " ", wd) # A stacked histogram with normed(displayed in percent) results: ax = WindroseAxes.from_ax() ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white') ax.set_legend() plt.show() # A windrose in filled representation, with a controled colormap # …or without filled regions ax = WindroseAxes.from_ax() ax.contour(wd, ws, bins=np.arange(0, 8, 1), cmap=cm.hot, lw=3) ax.set_legend() plt.show() print("###############################################################") print("###############################################################") print("###############################################################")
def Wind_Rose_Map(): import matplotlib.pyplot as plt from windrose import WindroseAxes import matplotlib.cm as cm # Create wind speed and direction variables ws = np.random.random(500) * 6 wd = np.random.random(500) * 360 ax = WindroseAxes.from_ax() ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white') ax.set_legend() plt.show()
def windrosebar(ws, wd): from windrose import WindroseAxes from matplotlib import pyplot as plt ax = WindroseAxes.from_ax() ax.bar(wd, ws, normed=True, opening=0.9, edgecolor='white') ax.set_legend() plt.show() bins = ax._info['bins'] direction = ax._info['dir'] table = ax._info['table'] print bins
def __init__(self): # Instantiate 2 figures # Figure 1: 2 subplots (Temp/Humidity and Rain) with 4 axis (ax1 - ax4) # Figure 2: 1 subplot (Windrose) with 1 axis (ax5) matplotlib.rcParams['timezone'] = '+2:00' self.hours = mdates.HourLocator(interval=1) self.h_fmt = mdates.DateFormatter('%H:%M') self.temp_rain_fig = plt.figure(figsize=(10, 15)) self.ax1 = plt.subplot(3, 1, 1) self.temp_rain_fig.add_axes(self.ax1) self.ax1.tick_params(axis='x', labelrotation=45) self.ax1.set_title("Temperature and Humidity") self.ax1.set_ylabel('Temp') self.ax1.grid(axis='y') self.ax2 = self.ax1.twinx() self.temp_rain_fig.add_axes(self.ax2) self.ax2.set_ylabel('Humidity', color='tab:red') # self.ax2.grid(axis='y') self.ax3 = plt.subplot(3, 1, 2, sharex=self.ax1) self.temp_rain_fig.add_axes(self.ax3) self.ax3.tick_params(axis='x', labelrotation=45) self.ax3.set_title("Rain") self.ax3.set_ylabel("Rain") self.ax3.grid(axis='y') self.ax4 = self.ax3.twinx() self.temp_rain_fig.add_axes(self.ax4) self.ax4.set_ylabel('Accumulated rain', color='tab:red') self.ax4.tick_params(axis='y', labelcolor='tab:red') self.ax5 = plt.subplot(3, 1, 3, sharex=self.ax1) self.temp_rain_fig.add_axes(self.ax5) self.ax5.tick_params(axis='x', labelrotation=45) self.ax5.set_title("Wind") self.ax5.set_ylabel("Wind force") self.ax5.grid(axis='y') self.windrose_fig = plt.figure(figsize=(5, 5)) self.wr_ax = WindroseAxes.from_ax(fig=self.windrose_fig, theta_labels=THETA_LABELS) self.windrose_fig.add_axes(self.wr_ax) self.wr_ax.set_title("Wind force and directions")
def show_wind_rose(data_tuples): ws = [(lambda x: x[3])(var) for var in data_tuples] wd = [(lambda x: x[4])(var) for var in data_tuples] ax = WindroseAxes.from_ax() ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white') ax.set_legend() plt.show()
def create_waverose_plot(name="person", data=None): wave_data = pd.DataFrame.from_dict(data) Dirp = pd.DataFrame.to_numpy(wave_data['Dirp'], dtype='float32') Hav = pd.DataFrame.to_numpy(wave_data['Hav'], dtype='float32') ax = WindroseAxes.from_ax() plt.title('Waverose-Plot') winter = cm = plt.get_cmap('winter') ax.bar(Dirp, Hav, normed=True, opening=0.8, edgecolor='white', cmap=winter) ax.set_legend() ax.set_xticklabels(['N', 'NW', 'W', 'SW', 'S', 'SE', 'E', 'NE']) ax.set_theta_zero_location('N') plt.xlabel('average wave height in [cm]', loc='left') plt.savefig('./generated/' + name + "_waverose_plot.png")
def plotWindRose(df, outDir): from windrose import WindroseAxes ax = WindroseAxes.from_ax() ax.bar(df.WND, df.WNS, normed=True, opening=0.9, bins = np.arange(0,35, 5), edgecolor='white') lgd = ax.legend(loc = (0.9,0.9), fontsize = 15, title = 'Windspeed (kph)') ax.set_xlabel(df['Locale'][0] + ' ' + str(df['LoggerID'][0]), fontsize = 18) plotStationName = df['Locale'][0] + '_' + str(df['LoggerID'][0]) + '_' plt.savefig(outDir + 'stationTS/' + plotStationName + 'Windrose.tif') plt.close()
def generate_figure(wd, ws, file_name): bins_range = np.arange(1, 6, 1) # this sets the legend scale fig, ax = plt.subplots() ax = WindroseAxes.from_ax() ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white') ax.set_legend() plt.savefig(file_name) #in case of memory leakage, which will always happen when running for many times plt.close('all') gc.collect()
def main1(): location = "Caen" # Octeville, Le Touquet filename = "./data/SM_{}_2009 UV.csv".format(location) dataframe = pandas.read_csv(filename, delimiter=";", header=None) df = dataframe.iloc[:, [3, 2]].copy() df.columns = ["direction", "speed"] # --- stacked histogram ax = WindroseAxes.from_ax() ax.bar(df.direction, df.speed, bins=np.arange(0, 20, 2), normed=False, opening=0.9) ax.set_legend() ax.set_title("Polar rose plot in {} (not normed)".format(location)) # --- Histogram presentation # ax = WindroseAxes.from_ax() # ax.bar(df.direction, df.speed, normed=True, nsector=16) # table = ax._info['table'] # wd_freq = np.sum(table, axis=0) # axis = plt.subplot() # wd_freq = np.sum(table, axis=0) # axis.bar(np.arange(16), wd_freq,) # xlabels = ('N', '', 'N-E', '', 'E', '', 'S-E', '', # 'S', '', 'S-W', '', 'W', '', 'N-W', '',) # xticks = np.arange(16) # axis.grid(axis='y') # axis.set_ylabel("Percentage (%)") # axis.set_yticks(np.arange(0,18,3)) # axis.set_xticks(xticks) # axis.set_xticklabels(xlabels) # axis.set_title("Frequency of wind directions in {}".format(location)) # PDF # from windrose import WindAxes # ax = WindAxes.from_ax() # # bins = np.arange(0, 6+1, 1) # # bins = bins[1:] # ax, params = ax.pdf(df.speed, bins=16) # # ax.legend(["Weibull dist: {}".format(params),]) # ax.set_title("PDF and fitting Weibull distribution for wind in {}".format( # location)) # ax.set_xlabel("Wind velocity (m/s)") # ax.set_ylabel("Probability") # print(params) plt.show()
def plot_windrose(self,windSpeed,windDirection,readData=True): """ Plot Windrose """ from windrose import WindroseAxes import matplotlib.cm as cm if readData: windSpeed = self.analyses.reader.get_timeseries(windSpeed,self.startDate,self.endDate) windDirection = self.analyses.reader.get_timeseries(windDirection,self.startDate,self.endDate) ax = WindroseAxes.from_ax() ax.bar(windDirection,windSpeed,normed=True,opening = 0.8, edgecolor='white') ax.set_legend()
def windrose_pa(name): dframe = indv_compound(name).join(wind_data()) #dframe = dframe[dframe['wd'] > 70][dframe['wd'] < 350] ax = WindroseAxes.from_ax() ax.bar(dframe['wd'].tolist(), dframe[f'{name}_pa'].tolist(), normed=True, opening=0.85, bins=10, nsector=32, cmap=cm.cool) ax.set_legend() plt.title('2018 Summit Wind Data') locs, labels = plt.yticks() new_labels = [str(s) + '%' for s in labels] for i in range(len(new_labels)): new_labels[i] = new_labels[i][12:15] + new_labels[i][17] plt.yticks(locs, labels=new_labels) plt.show()
def test_windrose_np_mpl_oo(): bins = np.arange(0, 8, 1) # windrose with scatter plot ax = WindroseAxes.from_ax() ax.scatter(wd, ws, alpha=0.2) ax.set_legend() plt.savefig("tests/output/oo/scatter.png") plt.close() # windrose like a stacked histogram with normed (displayed in percent) results ax = WindroseAxes.from_ax() ax.bar(wd, ws, normed=True, opening=0.8, edgecolor="white") ax.set_legend() plt.savefig("tests/output/oo/bar.png") plt.close() # Another stacked histogram representation, not normed, with bins limits ax = WindroseAxes.from_ax() ax.box(wd, ws, bins=bins) ax.set_legend() plt.savefig("tests/output/oo/box.png") plt.close() # A windrose in filled representation, with a controled colormap ax = WindroseAxes.from_ax() ax.contourf(wd, ws, bins=bins, cmap=cm.hot) ax.set_legend() plt.savefig("tests/output/oo/contourf.png") plt.close() # Same as above, but with contours over each filled region... ax = WindroseAxes.from_ax() ax.contourf(wd, ws, bins=bins, cmap=cm.hot) ax.contour(wd, ws, bins=bins, colors="black") ax.set_legend() plt.savefig("tests/output/oo/contourf-contour.png") plt.close() # ...or without filled regions ax = WindroseAxes.from_ax() ax.contour(wd, ws, bins=bins, cmap=cm.hot, lw=3) ax.set_legend() plt.savefig("tests/output/oo/contour.png") plt.close() # print ax._info # plt.show() ax = WindAxes.from_ax() bins = bins[1:] ax.pdf(ws, bins=bins) plt.savefig("tests/output/oo/pdf.png") plt.close()
def windrose_mr(compounds, start, end): for compound in compounds: compound_df = excel_voc(compound, start, end) compound_df.index = compound_df.index.strftime('%Y-%m-%d-%H') start_string = datetime.strptime( start, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d') end_string = datetime.strptime( end, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d') # dframe = compound_df.join(wind_data()) # dframe.dropna(inplace=True) # # dframe = dframe[dframe['wd'] > 72][dframe['wd'] < 342][dframe['ws'] > 1.0] # ax = WindroseAxes.from_ax() # ax.bar(dframe['wd'].tolist(), dframe[f'{compound}_mr'].tolist(), normed=True, opening=0.85, bins=10, nsector=32, # cmap=cm.cool) # ax.set_legend() # plt.title(f'Wind Data for {compound} ({start_string} to {end_string})') # locs, labels = plt.yticks() # new_labels = [str(s) + '%' for s in labels] # for i in range(len(new_labels)): # new_labels[i] = new_labels[i][12:15] + new_labels[i][17] # plt.yticks(locs, labels=new_labels) dframe = compound_df.join(wind_data()) dframe.dropna(inplace=True) dframe = dframe[dframe['wd'] > 72][dframe['wd'] < 342][ dframe['ws'] > 1.0] ax = WindroseAxes.from_ax() ax.bar(dframe['wd'].tolist(), dframe['ws'].tolist(), normed=True, opening=0.85, bins=10, nsector=32, cmap=cm.cool) ax.set_legend() plt.title(f'Cleaned Wind Data for all compounds') locs, labels = plt.yticks() new_labels = [str(s) + '%' for s in labels] for i in range(len(new_labels)): new_labels[i] = new_labels[i][12:15] + new_labels[i][17] plt.yticks(locs, labels=new_labels) plt.savefig( fr'C:\Users\ARL\Desktop\Summit\analyses\Connor\plots\windroses\all_compounds', dpi=600)
def flux_rose(Angle, PdfQ_tp, withaxe=0, place=None, fig=None, nsector=20, **kwargs): #### pdfQ flux distribution #### Corresponding angles in degree #### N bin nuber of bins for the rose #### withaxe : if 0, removes everything except the bars #### place :: where on the figure PdfQ = PdfQ_tp / np.nansum(PdfQ_tp) # normalization ######## creating the new pdf with the number of bins Lbin = 360 / nsector Bins = np.arange(0, 360, Lbin) Qdat = [] Qangle = [] precision_flux = 0.001 for n in range(len(Bins)): ind = np.argwhere((Angle >= Bins[n] - Lbin / 2) & (Angle < Bins[n] + Lbin / 2)) integral = int(np.nansum(PdfQ[ind]) / precision_flux) for i in range(integral): Qangle.append(Bins[n]) Qdat.append(1) Qangle = np.array(Qangle) #ax = plt.subplot(111, projection='polar') ax = WindroseAxes.from_ax(fig=fig) if place != None: ax.set_position(place, which='both') # bars = ax.bar(Angle, Intensity, normed=True, opening=1, edgecolor='k', nsector = Nsector, bins = Nbin, cmap = cmap) Qangle = (90 - Qangle) % 360 if Qangle.size != 0: bars = ax.bar(Qangle, Qdat, nsector=nsector, **kwargs) ax.set_rmin(0) plt.plot(0, 0, '.', color='w', zorder=100, markersize=3) ax.set_yticklabels([ '{:.1f}'.format(float(i.get_text()) * precision_flux) for i in ax.get_yticklabels() ]) if withaxe != 1: ax.set_yticks([]) return ax
def test_windrose_np_mpl_oo(): bins = np.arange(0, 8, 1) #windrose with scatter plot ax = WindroseAxes.from_ax() ax.scatter(wd, ws, alpha=0.2) ax.set_legend() plt.savefig('tests/output/oo/scatter.png') #windrose like a stacked histogram with normed (displayed in percent) results ax = WindroseAxes.from_ax() ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white') ax.set_legend() plt.savefig('tests/output/oo/bar.png') #Another stacked histogram representation, not normed, with bins limits ax = WindroseAxes.from_ax() ax.box(wd, ws, bins=bins) ax.set_legend() plt.savefig('tests/output/oo/box.png') #A windrose in filled representation, with a controled colormap ax = WindroseAxes.from_ax() ax.contourf(wd, ws, bins=bins, cmap=cm.hot) ax.set_legend() plt.savefig('tests/output/oo/contourf.png') #Same as above, but with contours over each filled region... ax = WindroseAxes.from_ax() ax.contourf(wd, ws, bins=bins, cmap=cm.hot) ax.contour(wd, ws, bins=bins, colors='black') ax.set_legend() plt.savefig('tests/output/oo/contourf-contour.png') #...or without filled regions ax = WindroseAxes.from_ax() ax.contour(wd, ws, bins=bins, cmap=cm.hot, lw=3) ax.set_legend() plt.savefig('tests/output/oo/contour.png') #print ax._info #plt.show() ax = WindAxes.from_ax() bins = bins[1:] ax.pdf(ws, bins=bins) plt.savefig('tests/output/oo/pdf.png')
def main(): # Create wind speed and direction variables N = 500 ws = np.random.random(N) * 6 wd = np.random.random(N) * 360 ax = WindroseAxes.from_ax() ax.scatter(wd, ws, alpha=0.2) ax.set_legend() # windrose like a stacked histogram with normed (displayed in percent) results ax = WindroseAxes.from_ax() ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white') ax.set_legend() # Another stacked histogram representation, not normed, with bins limits ax = WindroseAxes.from_ax() bins = np.arange(0, 8, 1) ax.box(wd, ws, bins=bins) ax.set_legend() # A windrose in filled representation, with a controled colormap ax = WindroseAxes.from_ax() ax.contourf(wd, ws, bins=bins, cmap=cm.hot) ax.set_legend() # Same as above, but with contours over each filled region... ax = WindroseAxes.from_ax() ax.contourf(wd, ws, bins=bins, cmap=cm.hot) ax.contour(wd, ws, bins=bins, colors='black') ax.set_legend() # ...or without filled regions ax = WindroseAxes.from_ax() ax.contour(wd, ws, bins=bins, cmap=cm.hot, lw=3) ax.set_legend() # print ax._info # plt.show() ax = WindAxes.from_ax() bins = np.arange(0, 6 + 1, 0.5) bins = bins[1:] ax.pdf(ws, bins=bins) plt.show()
def main(filename, exit_at, by, rmax, dpi, figsize, fps, bins_min, bins_max, bins_step, fontname, filename_out): # convert figsize (string like "8,9" to a list of float [8.0, 9.0] figsize = figsize.split(",") figsize = map(float, figsize) by_func = get_by_func(by) # Read CSV file to a Pandas DataFrame df_all = pd.read_csv(filename) df_all['Timestamp'] = pd.to_datetime(df_all['Timestamp']) df_all = df_all.set_index('Timestamp') df_all.index = df_all.index.tz_localize('UTC').tz_convert('UTC') dt_start = df_all.index[0] dt_end = df_all.index[-1] td = dt_end - dt_start Nslides = count(df_all, by_func) msg = """Starting First dt: %s Last dt: %s td: %s Slides: %d""" % (dt_start, dt_end, td, Nslides) logger.info(msg) # Define bins bins = np.arange(bins_min, bins_max, bins_step) # Create figure fig = plt.figure(figsize=figsize, dpi=dpi, facecolor='w', edgecolor='w') # Create a video writer (ffmpeg can create MPEG files) FFMpegWriter = matplotlib.animation.writers['ffmpeg'] metadata = dict(title='windrose', artist='windrose', comment="""Made with windrose http://www.github.com/scls19fr/windrose""") writer = FFMpegWriter(fps=fps, metadata=metadata) dt_start_process = datetime.datetime.now() with writer.saving(fig, filename_out, 100): try: for i, df in enumerate(generate(df_all, by_func)): dt1 = df.index[0] dt2 = df.index[-1] td = dt2 - dt1 msg = """ Slide %s/%s From %s to %s td %s""" % (i + 1, Nslides, dt1, dt2, td) logger.info(msg) remaining = Nslides - (i + 1) now = datetime.datetime.now() td_remaining = (now - dt_start_process) / (i + 1) * remaining logger.info(""" Expected time: %s end at: %s """ % (td_remaining, now + td_remaining)) title = " From %s\n to %s" % (dt1, dt2) try: ax = WindroseAxes.from_ax(fig=fig, rmax=rmax) # scatter, bar, box, contour, contourf direction = df['direction'].values var = df['speed'].values # ax.scatter(direction, var, alpha=0.2) # ax.set_xlim([-bins[-1], bins[-1]]) # ax.set_ylim([-bins[-1], bins[-1]]) # ax.bar(direction, var, bins=bins, normed=True, opening=0.8, edgecolor='white') # ax.box(direction, var, bins=bins) # ax.contour(direction, var, cmap=cm.hot, lw=3, bins=bins) ax.contourf(direction, var, bins=bins, cmap=cm.hot) ax.contour(direction, var, bins=bins, colors='black', lw=3) ax.set_legend() # ax = WindAxes.from_ax(fig=fig) # pdf: probability density function # ax.pdf(var, bins=bins) # ax.set_xlim([0, bins[-1]]) # ax.set_ylim([0, 0.4]) ax.set_title(title, fontname=fontname) writer.grab_frame() except KeyboardInterrupt: break except Exception: logger.error(traceback.format_exc()) fig.clf() if i > exit_at - 1 and exit_at != 0: # exit_at must be > 1 break except KeyboardInterrupt: return except Exception: logger.error(traceback.format_exc()) N = i + 1 logger.info("Number of slides: %d" % N) # plt.show() logger.info("Save file to '%s'" % filename_out)
def main(filename, dpi, figsize, fps, bins_min, bins_max, bins_step, filename_out): # convert figsize (string like "8,9" to a list of float [8.0, 9.0] figsize = figsize.split(",") figsize = map(float, figsize) # Read CSV file to a Pandas DataFrame df_all = pd.read_csv(filename) df_all['Timestamp'] = pd.to_datetime(df_all['Timestamp']) df_all = df_all.set_index('Timestamp') df_all.index = df_all.index.tz_localize('UTC').tz_convert('UTC') #df_all = df_all.iloc[-10000:,:] df_all = df_all['2011-07-01':'2011-12-31'] # Get Numpy arrays from DataFrame direction_all = df_all['direction'].values var_all = df_all['speed'].values index_all = df_all.index.to_datetime() #Fixed: .values -> to_datetime() by_all = df_all.index.map(by_func_monthly) by_unique = np.unique(by_all) print(by_unique) (ncols, nrows, nsheets) = (4, 3, 2) #layout = Layout(4, 3, 2) # ncols, nrows, nsheets layout = Layout(ncols, nrows, nsheets) def tuple_position(i, ncols, nrows): i_sheet, sheet_pos = divmod(i, ncols*nrows) i_row, i_col = divmod(sheet_pos, ncols) return i_sheet, i_row, i_col def position_from_tuple(t, ncols, nrows): i_sheet, i_row, i_col = t return i_sheet * ncols * nrows + i_row * ncols + i_col assert tuple_position(0, ncols, nrows) == (0, 0, 0) assert tuple_position(1, ncols, nrows) == (0, 0, 1) assert tuple_position(2, ncols, nrows) == (0, 0, 2) assert tuple_position(3, ncols, nrows) == (0, 0, 3) assert tuple_position(4, ncols, nrows) == (0, 1, 0) assert tuple_position(5, ncols, nrows) == (0, 1, 1) assert tuple_position(6, ncols, nrows) == (0, 1, 2) assert tuple_position(7, ncols, nrows) == (0, 1, 3) assert tuple_position(8, ncols, nrows) == (0, 2, 0) assert tuple_position(9, ncols, nrows) == (0, 2, 1) assert tuple_position(10, ncols, nrows) == (0, 2, 2) assert tuple_position(11, ncols, nrows) == (0, 2, 3) assert tuple_position(12, ncols, nrows) == (1, 0, 0) assert tuple_position(13, ncols, nrows) == (1, 0, 1) assert tuple_position(14, ncols, nrows) == (1, 0, 2) assert tuple_position(15, ncols, nrows) == (1, 0, 3) assert tuple_position(16, ncols, nrows) == (1, 1, 0) assert tuple_position(17, ncols, nrows) == (1, 1, 1) assert position_from_tuple((0, 0, 0), ncols, nrows) == 0 assert position_from_tuple((1, 0, 0), ncols, nrows) == ncols * nrows assert position_from_tuple((2, 0, 0), ncols, nrows) == 2 * ncols * nrows assert position_from_tuple((1, 0, 1), ncols, nrows) == ncols * nrows + 1 assert position_from_tuple((1, 1, 1), ncols, nrows) == ncols * nrows + ncols + 1 assert position_from_tuple((1, 2, 3), ncols, nrows) == ncols * nrows + 2 * ncols + 3 for i in range(20): t = tuple_position(i, ncols, nrows) assert position_from_tuple(t, ncols, nrows) == i #layout = NormalLayout() #with layout.append() as ax: # pass #layout.show() # Define bins bins = np.arange(bins_min, bins_max, bins_step) for by_value in by_unique: #by_value = (2011, 5) #mask = (by == by_value).all(axis=1) # ToFix: see http://stackoverflow.com/questions/32005403/boolean-indexing-with-numpy-array-and-tuples mask = (pd.Series(by_all) == by_value).values #print(mask) index = index_all[mask] var = var_all[mask] direction = direction_all[mask] # Create figure #fig = plt.figure(figsize=figsize, dpi=dpi, facecolor='w', edgecolor='w') #Same as above, but with contours over each filled region... ax = WindroseAxes.from_ax() ax.contourf(direction, var, bins=bins, cmap=cm.hot) ax.contour(direction, var, bins=bins, colors='black') fontname = "Courier" #title = by_value dt1 = index[0] dt2 = index[-1] #dt1 = df.index[mask][0] #dt2 = df.index[mask][-1] td = dt2 - dt1 title = "From %s\n to %s" % (dt1, dt2) ax.set_title(title, fontname=fontname) ax.set_legend() plt.show()
#!/usr/bin/env python # -*- coding: utf-8 -*- from windrose import WindroseAxes from windrose import WindAxes from matplotlib import pyplot as plt import matplotlib.cm as cm import numpy as np #Create wind speed and direction variables N = 500 ws = np.random.random(N) * 6 wd = np.random.random(N) * 360 ax = WindroseAxes.from_ax() ax.scatter(wd, ws, alpha=0.2) ax.set_legend() #windrose like a stacked histogram with normed (displayed in percent) results ax = WindroseAxes.from_ax() ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white') ax.set_legend() #Another stacked histogram representation, not normed, with bins limits ax = WindroseAxes.from_ax() bins = np.arange(0, 8, 1) ax.box(wd, ws, bins=bins) ax.set_legend() #A windrose in filled representation, with a controled colormap
def main(filename, exit_at, size, offset, dpi, figsize, fps, bins_min, bins_max, bins_step, filename_out): # convert figsize (string like "8,9" to a list of float [8.0, 9.0] figsize = figsize.split(",") figsize = map(float, figsize) # Read CSV file to a Pandas DataFrame df = pd.read_csv(filename) df['Timestamp'] = pd.to_datetime(df['Timestamp']) df = df.set_index('Timestamp') #df = df.iloc[-10000:,:] df.index = df.index.tz_localize('UTC').tz_convert('UTC') # Get Numpy arrays from DataFrame direction = df['direction'].values var = df['speed'].values index = df.index.values # Define bins bins = np.arange(bins_min, bins_max, bins_step) # Create figure fig = plt.figure(figsize=figsize, dpi=dpi, facecolor='w', edgecolor='w') # Create a video writer (ffmpeg can create MPEG files) FFMpegWriter = mpl.animation.writers['ffmpeg'] metadata = dict(title='windrose', artist='windrose', comment="""Made with windrose http://www.github.com/scls19fr/windrose""") writer = FFMpegWriter(fps=fps, metadata=metadata) dt0 = index[offset] print("size: %d" % size) print("offset: %d" % offset) print("First dt: %s" % dt0) print("") dt2 = None i = 0 with writer.saving(fig, filename_out, 100): #for i in range(1000): # 100 try: while True: # loop until fails (end of data) print("Processing %d" % (i + 1)) i1 = offset + i*size i2 = offset + (i+1)*size + 1 index_tmp = index[i1:i2] dt1 = index_tmp[0] dt2 = index_tmp[-1] td = dt2 - dt1 title = """ From %s to %s""" % (dt1, dt2) print(title) print(""" td %r""" % td.astype('timedelta64[m]')) try: direction_tmp = direction[i1:i2] var_tmp = var[i1:i2] ax = WindroseAxes.from_ax(fig=fig) # scatter, bar, box, contour, contourf #ax.scatter(direction_tmp, var_tmp, alpha=0.2) #ax.set_xlim([-bins[-1], bins[-1]]) #ax.set_ylim([-bins[-1], bins[-1]]) #ax.bar(direction_tmp, var_tmp, bins=bins, normed=True, opening=0.8, edgecolor='white') #ax.box(direction_tmp, var_tmp, bins=bins) #ax.contour(direction_tmp, var_tmp, cmap=cm.hot, lw=3, bins=bins) ax.contourf(direction_tmp, var_tmp, bins=bins, cmap=cm.hot) ax.contour(direction_tmp, var_tmp, bins=bins, colors='black', lw=3) ax.set_legend() #ax = WindAxes.from_ax(fig=fig) # pdf: probability density function #ax.pdf(var_tmp, bins=bins) #ax.set_xlim([0, bins[-1]]) #ax.set_ylim([0, 0.4]) ax.set_title(title, fontname="Courier New") writer.grab_frame() except: print(traceback.format_exc(), file=sys.stderr) print("") fig.clf() i += 1 if i == exit_at - 1: # exit_at must be > 1 break except: print(traceback.format_exc(), file=sys.stderr) print("First dt: %r" % dt0) print("Last dt: %r" % dt2) td = dt2 - dt0 print(" td: %r" % td.astype('timedelta64[D]')) N = i + 1 print("Number of slides: %d" % N) #plt.show() print("") print("Save file to '%s'" % filename_out)
def conditional_rate_of_occurrence(self, ds, t_window=pd.Timedelta(minutes=15), symmetric_t_window=False, dist_window=20, dim='speed', max_dim=200, windrose=True, **kwargs): ''' Calculate the conditional rate of occurence Parameters ---------- ds: dataset with coordinates lat, lon, and time t_window: pd.Timedelta of time window used to check for occurrences symmetric_t_window: bool indicating whether to look backwards in time dist_window: radius in km of window in which to check for occurrences dim: str dimension to pass to windrose -- 'speed', 'dist', 'hours', or 'minutes' max_dim: max dim to include in windrose can be set to None windrose: bool indicating whether or not to plot windrose **kwargs: passed on to windrose function Returns ------- plot: windrose plot OR df: pandas.Dataframe containing bearing and dim info ''' from geopy.distance import vincenty, great_circle zero_time = pd.Timedelta(seconds=0).asm8 t_window = t_window.asm8 if symmetric_t_window: t_window = t_window/2 lon = ds.lon.values lat = ds.lat.values time = ds.time.values loc = np.stack([lat, lon]).T dists = [] bearings = [] speeds = [] t_diffs = [] for t in time: if symmetric_t_window: t_diff = np.abs(time-t) else: t_diff = time-t bool_a = np.where((zero_time < t_diff) & (t_diff < t_window)) little_loc = np.take(loc, bool_a, axis=0)[0] little_t_diff = np.take(t_diff, bool_a)[0] for ll, tt in zip(little_loc[1:], little_t_diff[1:]): if (ll == little_loc[0]).all(): continue dist = great_circle(little_loc[0], ll).km if dist < dist_window: hours = (int(tt)/10e8/60/60.) t_diffs.append(hours) dists.append(dist) speeds.append(dist/hours) bearings.append(calculate_bearing(little_loc[0], ll)) df = pd.DataFrame({'speed': speeds, 'dist': dists, 'hours': t_diffs, 'direction': bearings}) if dim == 'minutes': df = df.assign(minutes=df.hours*60) if not windrose: return df else: from windrose import WindroseAxes if max_dim is not None: df = df[df[dim].abs() < max_dim] max_dim = max_dim or df[dim].abs().max() ax = WindroseAxes.from_ax() ax.bar(df['direction'], df[dim], bins=kwargs.pop('bins', np.arange(0, max_dim, 20)), normed=kwargs.pop('normed', True), opening=kwargs.pop('opening', 0.9), edgecolor=kwargs.pop('edgecolor', 'white'), **kwargs) ax.set_legend() return ax