### Install Latest Development Version via Clone and Setup Source: https://github.com/python-windrose/windrose/blob/main/README.md Alternatively, clone the repository and install the development version using setup.py. This method provides more control over the installation process. ```bash git clone https://github.com/python-windrose/windrose python setup.py install ``` -------------------------------- ### Install Latest Development Version from Source Source: https://github.com/python-windrose/windrose/blob/main/CONTRIBUTING.md Clone the repository and install the latest development version locally. This method is useful if you plan to make code changes or need to inspect the source code. ```bash $ git clone https://github.com/python-windrose/windrose $ python setup.py install ``` -------------------------------- ### Install development version Source: https://github.com/python-windrose/windrose/blob/main/docs/development.md Install the package in editable mode or directly from the remote repository. ```bash $ python -m pip install . ``` ```bash $ python -m pip install git+https://github.com/python-windrose/windrose.git ``` -------------------------------- ### Install Latest Development Version with pip Source: https://github.com/python-windrose/windrose/blob/main/CONTRIBUTING.md Use this command to install the latest development version of the python-windrose library directly from GitHub using pip. Ensure you have pip installed. ```bash $ pip install git+https://github.com/python-windrose/windrose ``` -------------------------------- ### Install Windrose using pip Source: https://github.com/python-windrose/windrose/blob/main/docs/install.md Install the latest release version of the windrose package from PyPi using pip. ```bash pip install windrose ``` -------------------------------- ### Install Latest Development Version via Git Source: https://github.com/python-windrose/windrose/blob/main/README.md Install the most recent development version directly from the GitHub repository. This is useful for testing new features or contributing to the project. ```bash pip install git+https://github.com/python-windrose/windrose ``` -------------------------------- ### Building and uploading to PyPI manually Source: https://github.com/python-windrose/windrose/blob/main/release-procedure.md Clean the workspace, build the distribution files, and upload them using twine. ```bash git clean -xfd python -m build --sdist --wheel . --outdir dist python -m twine check dist/* python -m twine upload dist/* ``` -------------------------------- ### Clone the repository Source: https://github.com/python-windrose/windrose/blob/main/docs/development.md Use these commands to download the source code and navigate into the project directory. ```bash $ git clone https://github.com/python-windrose/windrose.git $ cd windrose ``` -------------------------------- ### Generate Random Wind Data Source: https://github.com/python-windrose/windrose/blob/main/notebooks/usage.ipynb Generates random wind speed and direction data using NumPy. This is useful for testing and examples when real data is not immediately available. ```python import numpy as np N = 500 ws = np.random.random(N) * 6 wd = np.random.random(N) * 360 ``` -------------------------------- ### Configuring .pypirc for manual upload Source: https://github.com/python-windrose/windrose/blob/main/release-procedure.md Define the index servers and credentials in the ~/.pypirc file to enable manual package distribution. ```ini [distutils] # this tells distutils what package indexes you can push to index-servers = pypi pypi # the live PyPI pypitest # test PyPI [pypi] repository:http://pypi.python.org/pypi username:scls password:********** ``` -------------------------------- ### Tagging a release via CLI Source: https://github.com/python-windrose/windrose/blob/main/release-procedure.md Use these commands to create a local git tag and push it to the remote repository. ```bash git tag -a x.x.x -m 'Version x.x.x' git push windrose master --tags ``` -------------------------------- ### Create Inset Windrose Axes Source: https://github.com/python-windrose/windrose/blob/main/notebooks/usage.ipynb Demonstrates how to create inset axes for windrose plots, either with fixed sizes or relative to the main axes. Requires `windrose` and `mpl_toolkits.axes_grid1.inset_locator`. ```python from mpl_toolkits.axes_grid1.inset_locator import inset_axes import windrose # Coordinates of the station we were measuring windspeed cham_lon, cham_lat = (6.8599, 45.9259) passy_lon, passy_lat = (6.7, 45.9159) # Inset axe it with a fixed size wrax_cham = inset_axes( main_ax, width=1, # size in inches height=1, # size in inches loc="center", # center bbox at given position bbox_to_anchor=(cham_lon, cham_lat), # position of the axe bbox_transform=main_ax.transData, # use data coordinate (not axe coordinate) axes_class=windrose.WindroseAxes, # specify the class of the axe ) # Inset axe with size relative to main axe height_deg = 0.1 wrax_passy = inset_axes( main_ax, width="100%", # size in % of bbox height="100%", # size in % of bbox # loc="center", # don"t know why, but this doesn"t work. # specify the center lon and lat of the plot, and size in degree bbox_to_anchor=( passy_lon - height_deg / 2, passy_lat - height_deg / 2, height_deg, height_deg, ), bbox_transform=main_ax.transData, axes_class=windrose.WindroseAxes, ) wrax_cham.bar(wd, ws) wrax_passy.bar(wd, ws) for ax in [wrax_cham, wrax_passy]: ax.tick_params(labelleft=False, labelbottom=False) ``` -------------------------------- ### Run unit tests Source: https://github.com/python-windrose/windrose/blob/main/docs/development.md Execute the test suite using pytest to verify library functionality. ```bash $ python -m pytest -vv tests ``` ```bash $ python -m pytest -vv tests/test_windrose.py::test_windrose_np_plot_and_pd_plot ``` -------------------------------- ### Basic Windrose Plotting Source: https://github.com/python-windrose/windrose/blob/main/notebooks/usage.ipynb Demonstrates how to create a basic windrose plot using provided wind direction and speed data. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of new user accounts. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new account. - **email** (string) - Required - The email address for the account. - **password** (string) - Required - The password for the account. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201) - **id** (integer) - The unique identifier for the newly created user. - **username** (string) - The username of the created account. - **email** (string) - The email address of the created account. #### Response Example ```json { "id": 123, "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Load Wind Data with Pandas Source: https://github.com/python-windrose/windrose/blob/main/notebooks/windrose_sample_poitiers_csv.ipynb Loads a sample wind dataset from a CSV URL and sets the timestamp as the index. ```python import pandas as pd url = "https://github.com/python-windrose/windrose/raw/main/samples/sample_wind_poitiers.csv" df = pd.read_csv(url, parse_dates=["Timestamp"]) df = df.set_index("Timestamp") df ``` -------------------------------- ### Set up Main Axes for Map Overlay Source: https://github.com/python-windrose/windrose/blob/main/notebooks/usage.ipynb Initializes a matplotlib figure and axes with a Cartopy projection for overlaying geographical data. This sets the extent, gridlines, and adds coastlines and a map tile layer. ```python import cartopy.crs as ccrs import cartopy.io.img_tiles as cimgt import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.axes_grid1.inset_locator import inset_axes import windrose ws = np.random.random(500) * 6 wd = np.random.random(500) * 360 minlon, maxlon, minlat, maxlat = (6.5, 7.0, 45.85, 46.05) proj = ccrs.PlateCarree() fig = plt.figure(figsize=(12, 6)) # Draw main ax on top of which we will add windroses main_ax = fig.add_subplot(1, 1, 1, projection=proj) main_ax.set_extent([minlon, maxlon, minlat, maxlat], crs=proj) main_ax.gridlines(draw_labels=True) main_ax.coastlines() request = cimgt.OSM() main_ax.add_image(request, 12) ``` -------------------------------- ### Define and Inspect Bins Source: https://github.com/python-windrose/windrose/blob/main/notebooks/windrose_sample_poitiers_csv.ipynb Creates a range of bins for histogram calculations. ```python bins = np.arange(0, 30 + 1, 1) bins = bins[1:] bins ``` -------------------------------- ### Plot PDF and Weibull Fitting Source: https://context7.com/python-windrose/windrose/llms.txt Use WindAxes or wrpdf to visualize wind speed probability density and calculate Weibull distribution parameters. ```python from windrose import WindAxes, wrpdf import numpy as np import matplotlib.pyplot as plt # Generate Weibull-like wind data ws = np.random.weibull(2, 1000) * 8 # Method 1: Using WindAxes class directly ax = WindAxes.from_ax() bins = np.arange(0, 15, 1) ax, params = ax.pdf(ws, bins=bins, Nx=100, bar_color="blue", plot_color="red") print(f"Weibull parameters: shape={params[1]:.2f}, scale={params[3]:.2f}") plt.title("Wind Speed Distribution with Weibull Fit") plt.xlabel("Wind Speed (m/s)") plt.ylabel("Probability Density") plt.show() # Method 2: Using convenience function ax, params = wrpdf(ws, bins=bins) plt.show() ``` -------------------------------- ### Print Weibull Distribution Parameters Source: https://github.com/python-windrose/windrose/blob/main/notebooks/usage.ipynb Displays the optimal parameters calculated for the Weibull distribution of wind speed data. This is typically used after computing the PDF. ```python print(f"{params=}") ``` -------------------------------- ### Probability Density Function (PDF) and Weibull Fitting Source: https://github.com/python-windrose/windrose/blob/main/notebooks/usage.ipynb Details on calculating the probability density function for wind speeds and fitting the Weibull distribution, including accessing optimal parameters. ```APIDOC ## PUT /api/users/{id} ### Description Updates an existing user account. ### Method PUT ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to update. #### Request Body - **username** (string) - Optional - The new username for the account. - **email** (string) - Optional - The new email address for the account. ### Request Example ```json { "email": "john.doe.updated@example.com" } ``` ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the user. - **username** (string) - The updated username. - **email** (string) - The updated email address. #### Response Example ```json { "id": 123, "username": "johndoe", "email": "john.doe.updated@example.com" } ``` ``` -------------------------------- ### WindroseAxes.pdf Source: https://github.com/python-windrose/windrose/blob/main/docs/api.md Draws the probability density function and returns Weibull distribution parameters. ```APIDOC ## windrose.WindAxes.pdf(var, bins=None, Nx=100, bar_color='b', plot_color='g', Nbins=10, *args, **kwargs) ### Description Draws the probability density function (PDF) of the wind data and returns the calculated Weibull distribution parameters. ### Method INSTANCE METHOD ### Endpoint N/A (Method within a class) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters * **var** - The wind speed data. * **bins** (optional) - Bin edges for the histogram. * **Nx** (int) - Optional. Default is 100. Number of points for the PDF curve. * **bar_color** (str) - Optional. Default is 'b'. Color for the histogram bars. * **plot_color** (str) - Optional. Default is 'g'. Color for the PDF curve. * **Nbins** (int) - Optional. Default is 10. Number of bins for the histogram. * **args** - Variable positional arguments. * **kwargs** - Variable keyword arguments. ### Request Example ```python import matplotlib.pyplot as plt import numpy as np from windrose import WindroseAxes # Sample wind speed data ws = np.random.rand(100) * 20 wd = np.random.rand(100) * 360 fig = plt.figure() ax = fig.add_subplot(111, polar=True) wr = WindroseAxes.from_ax(ax=ax) wr.pdf(ws, bins=np.arange(0, 22, 2), plot_color='red', bar_color='blue') plt.show() ``` ### Response #### Success Response (200) - **Weibull distribution parameters**: The calculated parameters of the Weibull distribution. #### Response Example N/A (Return value is data, not a JSON object) ``` -------------------------------- ### Handle Calm Wind Conditions Source: https://context7.com/python-windrose/windrose/llms.txt Filter low wind speeds using the calm_limit parameter to display calm conditions as a centered circle. ```python from windrose import WindroseAxes import numpy as np import matplotlib.pyplot as plt # Generate data with many calm conditions ws = np.concatenate([ np.random.uniform(0, 1, 200), # Calm winds np.random.weibull(2, 300) * 8 # Regular winds ]) wd = np.random.random(500) * 360 ax = WindroseAxes.from_ax() ``` -------------------------------- ### wrbox Source: https://github.com/python-windrose/windrose/blob/main/docs/api.md Plots a windrose in proportional box mode, showing colored boxes for each variable bin and sector. ```APIDOC ## wrbox ### Description Plot a windrose in proportional box mode. For each var bins and for each sector, a colored box will be draw on the axes. ### Parameters - **direction** (1D array) - Directions the wind blows from, North centered. - **var** (1D array) - Values of the variable to compute. Typically the wind speeds. - **ax** (matplotlib.axes.Axes, optional) - The axes to plot on. If None, a new figure and axes are created. - **rmax** (float, optional) - Maximum value for the radius of the windrose plot. - **figsize** (tuple, optional) - Figure size. Defaults to (8, 8). - **nsector** (integer, optional) - Number of sectors used to compute the windrose table. Defaults to 16. - **sectoroffset** (float, optional) - The offset for the sectors. Defaults to 0. - **bins** (1D array or integer, optional) - Number of bins, or a sequence of bins variable. Defaults to 6. - **blowto** (bool, optional) - If True, the windrose will be pi rotated to show where the wind blows to. - **colors** (string or tuple, optional) - Color(s) for the boxes. - **cmap** (matplotlib.cm.Colormap, optional) - Colormap instance if colors are not specified. - **edgecolor** (string, optional) - The string color for each edge bar. Defaults to no edgecolor. - **calm_limit** (float, optional) - Calm limit for the var parameter. If not None, a centered red circle will be drawn for calms. ``` -------------------------------- ### Create Bar Windrose Source: https://context7.com/python-windrose/windrose/llms.txt Generates a normalized bar chart windrose using sample wind data. Ensure WindroseAxes is imported and initialized from a Matplotlib axes object. ```python import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from windrose import WindroseAxes # Generate sample wind data np.random.seed(42) N = 500 wind_speed = np.random.random(N) * 6 # Wind speeds 0-6 m/s wind_direction = np.random.random(N) * 360 # Directions 0-360 degrees # Create WindroseAxes from scratch ax = WindroseAxes.from_ax() # Create bar windrose with normalized values (displayed in percent) ax.bar(wind_direction, wind_speed, normed=True, opening=0.8, edgecolor="white") ax.set_legend() plt.title("Wind Rose - Bar Chart (Normalized)") plt.show() ``` -------------------------------- ### Generate Wind Rose from Statistical Data Source: https://context7.com/python-windrose/windrose/llms.txt Plot wind roses using pre-computed statistical parameters like mean speeds and frequencies instead of raw data points. ```python from windrose import WindroseAxes import numpy as np import matplotlib.pyplot as plt # Pre-computed statistical wind data by direction sector # Directions in degrees (72 sectors = 5 degrees each) directions = np.arange(0, 360, 5) # Mean wind speeds for each direction mean_speeds = 8 + 4 * np.sin(np.radians(directions)) # Example pattern # Frequency of each direction (must sum to ~1.0) frequencies = np.ones(72) / 72 ax = WindroseAxes.from_ax() ax.box( directions, mean_speeds, frequency=frequencies, mean_values=True, # Input is mean values, not raw data bins=[6, 8, 10, 12, 14], nsector=72 ) ax.set_legend(units="m/s") plt.title("Wind Rose from Statistical Input") plt.show() ``` -------------------------------- ### Visualize Wind Scatter Plot Source: https://github.com/python-windrose/windrose/blob/main/notebooks/windrose_sample_poitiers_csv.ipynb Creates a scatter plot of wind vector components with equal aspect ratio. ```python from matplotlib import pyplot as plt fig, ax = plt.subplots(figsize=(8, 8), dpi=80) x0, x1 = ax.get_xlim() y0, y1 = ax.get_ylim() ax.set_aspect("equal") df.plot(kind="scatter", x="speed_x", y="speed_y", alpha=0.05, ax=ax) Vw = 80 ax.set_xlim([-Vw, Vw]) ax.set_ylim([-Vw, Vw]); ``` -------------------------------- ### Stacked Histogram with Normed Results Source: https://github.com/python-windrose/windrose/blob/main/notebooks/usage.ipynb Creates a stacked histogram of wind speed and direction, with results normalized to display percentages. Ensure WindroseAxes is imported. ```python from windrose import WindroseAxes ax = WindroseAxes.from_ax() ax.bar(wd, ws, normed=True, opening=0.8, edgecolor="white") ax.set_legend() ``` -------------------------------- ### Stacked Histogram with Bins Source: https://github.com/python-windrose/windrose/blob/main/notebooks/usage.ipynb Generates a stacked histogram using specified bin limits for wind speed and direction. The results are not normed. ```python ax = WindroseAxes.from_ax() ax.box(wd, ws, bins=np.arange(0, 8, 1)) ax.set_legend() ``` -------------------------------- ### Create Box Plot Windrose Source: https://context7.com/python-windrose/windrose/llms.txt Generates a proportional box windrose where box widths correspond to wind speed bins. This visualization clearly distinguishes speed categories. Requires WindroseAxes. ```python from windrose import WindroseAxes import numpy as np ws = np.random.weibull(2, 500) * 8 wd = np.random.random(500) * 360 ax = WindroseAxes.from_ax() bins = np.arange(0, 10, 2) ax.box(wd, ws, bins=bins, edgecolor="black") ax.set_legend() plt.title("Wind Rose - Box Plot") plt.show() ``` -------------------------------- ### windrose.wrpdf Source: https://github.com/python-windrose/windrose/blob/main/docs/api.md Draws probability density function and returns Weibull distribution parameters. ```APIDOC ## windrose.wrpdf ### Description Draw probability density function and return Weibull distribution parameters. ``` -------------------------------- ### Calculate Probability Density Function (PDF) of Wind Speed Source: https://github.com/python-windrose/windrose/blob/main/notebooks/usage.ipynb Computes the probability density function for wind speed data using specified bins. This method returns the axes object and the calculated Weibull distribution parameters. ```python from windrose import WindAxes ax = WindAxes.from_ax() bins = np.arange(0, 6 + 1, 0.5) bins = bins[1:] ax, params = ax.pdf(ws, bins=bins) ``` -------------------------------- ### Generate Wind Rose PDF Plot Source: https://github.com/python-windrose/windrose/blob/main/notebooks/windrose_sample_poitiers_csv.ipynb Creates a probability density function plot for wind speed. ```python plot_windrose(df, kind="pdf", bins=np.arange(0.01, 30, 1)); ``` -------------------------------- ### Overlaying Windrose on a Map Source: https://github.com/python-windrose/windrose/blob/main/notebooks/usage.ipynb Illustrates how to overlay a windrose plot on top of a map visualization using matplotlib's inset_axes utilities and cartopy. ```APIDOC ## DELETE /api/users/{id} ### Description Deletes a user account. ### Method DELETE ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to delete. ### Response #### Success Response (204) No content is returned upon successful deletion. #### Response Example (No content) ``` -------------------------------- ### Integrate and Clean Pandas Data Source: https://context7.com/python-windrose/windrose/llms.txt Prepare time-series wind data by cleaning NaN values before plotting with the windrose library. ```python import pandas as pd import numpy as np from windrose import plot_windrose, clean_df import matplotlib.pyplot as plt # Load wind data from CSV (example structure) # Timestamp,speed,direction # 2014-01-01 00:00:00,5.2,180 # 2014-01-01 01:00:00,4.8,175 # Create sample DataFrame simulating real data dates = pd.date_range("2014-01-01", periods=1000, freq="h") df = pd.DataFrame({ "Timestamp": dates, "speed": np.random.weibull(2, 1000) * 8, "direction": np.random.random(1000) * 360 }) df = df.set_index("Timestamp") # Add some NaN values to simulate real data df.loc[df.sample(50).index, "speed"] = np.nan # Clean the DataFrame (remove NaN and zero values) df_clean = clean_df(df, var="speed", direction="direction") print(f"Original: {len(df)} rows, Cleaned: {len(df_clean)} rows") # Plot the windrose ax = plot_windrose(df_clean, kind="bar", var_name="speed", direction_name="direction", normed=True) plt.title("Cleaned Wind Data") plt.show() ``` -------------------------------- ### box(direction, var, **kwargs) Source: https://github.com/python-windrose/windrose/blob/main/docs/api.md Plots a windrose in proportional box mode. For each variable bin and each sector, a colored box is drawn on the axes. ```APIDOC ## POST /windrose/box ### Description Plots a windrose in proportional box mode. For each variable bin and each sector, a colored box is drawn on the axes. ### Method POST ### Endpoint /windrose/box ### Parameters #### Request Body - **direction** (1D array) - Required - Directions the wind blows from, North centered. - **var** (1D array) - Required - Values of the variable to compute. Typically the wind speeds. - **nsector** (integer) - Optional - Number of sectors used to compute the windrose table. Defaults to 16. - **sectoroffset** (float) - Optional - The offset for the sectors. Defaults to 0. - **bins** (1D array or integer) - Optional - Number of bins, or a sequence of bins variable. Defaults to 6. - **blowto** (bool) - Optional - If True, the windrose will be pi rotated to show where the wind blows to. - **colors** (string or tuple) - Optional - Color(s) for the boxes. Can be a single string color or a tuple of matplotlib color arguments. - **cmap** (matplotlib.cm Colormap instance) - Optional - Colormap to use if colors is None. Defaults to a matplotlib default. - **edgecolor** (string) - Optional - The color of the edge of each box. Defaults to no edgecolor. - **calm_limit** (float) - Optional - Calm limit for the var parameter. Data below this value is removed from computation. If not None, a centered red circle is drawn for calm occurrences. ``` -------------------------------- ### Configure Wind Rose Legend Source: https://context7.com/python-windrose/windrose/llms.txt Customize legend properties such as bins and opening to refine the visual presentation of the wind rose. ```python from windrose import WindroseAxes import numpy as np import matplotlib.pyplot as plt ws = np.random.weibull(2, 500) * 10 wd = np.random.random(500) * 360 ax = WindroseAxes.from_ax() ax.bar(wd, ws, bins=np.arange(0, 12, 2), normed=True, opening=0.8) ``` -------------------------------- ### WindroseAxes.from_ax Source: https://github.com/python-windrose/windrose/blob/main/docs/api.md Creates a WindroseAxes instance from an existing Matplotlib Axes. ```APIDOC ## static windrose.WindAxes.from_ax(ax=None, fig=None, figsize=(8, 8), *args, **kwargs) ### Description Creates a WindroseAxes instance, optionally from an existing Matplotlib Axes or Figure. ### Method STATIC ### Endpoint N/A (Static method within a class) ### Parameters * **ax** (matplotlib.Axes) - Optional - An existing Matplotlib Axes object. * **fig** (matplotlib.figure.Figure) - Optional - A Matplotlib Figure object. * **figsize** (tuple) - Optional - Default is (8, 8). The size of the figure if a new one is created. * **args** - Variable positional arguments. * **kwargs** - Variable keyword arguments. ### Request Example ```python import matplotlib.pyplot as plt from windrose import WindAxes fig, ax = plt.subplots() windrose_ax = WindAxes.from_ax(ax=ax) ``` ### Response #### Success Response (200) - **WindroseAxes** object: An instance of WindroseAxes. #### Response Example N/A (Object instantiation) ``` -------------------------------- ### WindroseAxes Class Source: https://github.com/python-windrose/windrose/blob/main/docs/api.md Class for creating and managing windrose axes. ```APIDOC ## class windrose.WindroseAxes(*args, **kwargs) ### Description Initializes and creates a windrose axes object. ### Method N/A (Class definition) ### Endpoint N/A (Class definition) ### Parameters N/A (Class definition) ### Request Example N/A (Class definition) ### Response N/A (Class definition) ``` -------------------------------- ### Create Filled Contour Windrose Source: https://context7.com/python-windrose/windrose/llms.txt Generates a filled contour windrose using specified wind data, bins, and colormap. Contour lines can be added for better clarity. Ensure WindroseAxes is imported and initialized. ```python from windrose import WindroseAxes import numpy as np import matplotlib.cm as cm ws = np.random.weibull(2, 1000) * 10 wd = np.random.random(1000) * 360 ax = WindroseAxes.from_ax() bins = np.arange(0, 12, 2) # Filled contour plot with hot colormap ax.contourf(wd, ws, bins=bins, cmap=cm.hot) # Add contour lines for clarity ax.contour(wd, ws, bins=bins, colors="black", linewidths=0.5) ax.set_legend() plt.title("Wind Rose - Filled Contour") plt.show() ``` -------------------------------- ### WindAxes Factory Source: https://github.com/python-windrose/windrose/blob/main/docs/api.md Factory class for creating WindroseAxes or WindAxes. ```APIDOC ## static windrose.WindAxesFactory.create(typ, ax=None, *args, **kwargs) ### Description Factory method to create either a WindroseAxes or a WindAxes object. ### Method STATIC ### Endpoint N/A (Static method within a class) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters * **typ** (string) - Required - Type of axes to create. Accepts 'windroseaxes' or 'windaxes'. * **ax** (matplotlib.Axes) - Optional - An existing Matplotlib Axes object to use. ### Request Example ```python from windrose import WindAxesFactory # Create a WindroseAxes windrose_ax = WindAxesFactory.create('windroseaxes') # Create a WindAxes wind_ax = WindAxesFactory.create('windaxes') ``` ### Response #### Success Response (200) - **WindroseAxes** or **WindAxes** object: The created axes object. #### Response Example N/A (Object instantiation) ``` -------------------------------- ### Plot Wind Rose by Month Source: https://github.com/python-windrose/windrose/blob/main/notebooks/windrose_sample_poitiers_csv.ipynb Filters data by year and month to generate specific wind rose plots. ```python def plot_month(df, t_year_month, *args, **kwargs): by = "year_month" df[by] = df.index.map(lambda dt: (dt.year, dt.month)) df_month = df[df[by] == t_year_month] ax = plot_windrose(df_month, *args, **kwargs) return ax plot_month(df, (2014, 7), kind="contour", bins=np.arange(0, 10, 1), cmap=cm.hot); ``` ```python plot_month(df, (2014, 8), kind="contour", bins=np.arange(0, 10, 1), cmap=cm.hot); ``` ```python plot_month(df, (2014, 9), kind="contour", bins=np.arange(0, 10, 1), cmap=cm.hot); ``` -------------------------------- ### wrbar Source: https://github.com/python-windrose/windrose/blob/main/docs/api.md Plots a windrose in bar mode, showing colored bars for each variable bin and sector. ```APIDOC ## wrbar ### Description Plot a windrose in bar mode. For each var bins and for each sector, a colored bar will be draw on the axes. ### Parameters - **direction** (1D array) - Directions the wind blows from, North centered. - **var** (1D array) - Values of the variable to compute. Typically the wind speeds. - **ax** (matplotlib.axes.Axes, optional) - The axes to plot on. If None, a new figure and axes are created. - **rmax** (float, optional) - Maximum value for the radius of the windrose plot. - **figsize** (tuple, optional) - Figure size. Defaults to (8, 8). - **nsector** (integer, optional) - Number of sectors used to compute the windrose table. Defaults to 16. - **sectoroffset** (float, optional) - The offset for the sectors. Defaults to 0. - **bins** (1D array or integer, optional) - Number of bins, or a sequence of bins variable. Defaults to 6. - **blowto** (bool, optional) - If True, the windrose will be pi rotated to show where the wind blows to. - **colors** (string or tuple, optional) - Color(s) for the bars. - **cmap** (matplotlib.cm.Colormap, optional) - Colormap instance if colors are not specified. - **edgecolor** (string, optional) - The string color for each edge box. Defaults to no edgecolor. - **opening** (float, optional) - Controls the space between each sector (1.0 for no space). Between 0.0 and 1.0. - **calm_limit** (float, optional) - Calm limit for the var parameter. If not None, a centered red circle will be drawn for calms. ``` -------------------------------- ### Create Multi-Plot Windrose Figures Source: https://context7.com/python-windrose/windrose/llms.txt Utilize convenience wrapper functions to generate bar, contour, box, and filled contour plots on a single figure. ```python from windrose import wrbar, wrcontourf, wrbox, wrcontour import numpy as np import matplotlib.cm as cm import matplotlib.pyplot as plt ws = np.random.weibull(2, 500) * 8 wd = np.random.random(500) * 360 bins = np.arange(0, 10, 2) # Create 2x2 subplot comparing different plot types fig = plt.figure(figsize=(12, 12)) # Bar plot ax1 = fig.add_subplot(2, 2, 1, projection="windrose") ax1.bar(wd, ws, bins=bins, normed=True, opening=0.8) ax1.set_legend() ax1.set_title("Bar") # Filled contour ax2 = fig.add_subplot(2, 2, 2, projection="windrose") ax2.contourf(wd, ws, bins=bins, cmap=cm.hot) ax2.set_legend() ax2.set_title("Contourf") # Box ax3 = fig.add_subplot(2, 2, 3, projection="windrose") ax3.box(wd, ws, bins=bins) ax3.set_legend() ax3.set_title("Box") # Contour ax4 = fig.add_subplot(2, 2, 4, projection="windrose") ax4.contour(wd, ws, bins=bins, cmap=cm.cool, linewidths=2) ax4.set_legend() ax4.set_title("Contour") plt.tight_layout() plt.show() ``` -------------------------------- ### Configure Calm Limit in Wind Rose Source: https://context7.com/python-windrose/windrose/llms.txt Use calm_limit to exclude low-speed values from the plot and display the percentage of calm conditions in the center. ```python ax.bar(wd, ws, bins=np.arange(1, 10, 2), normed=True, calm_limit=1.0, opening=0.8) ax.set_legend(units="m/s") plt.title("Wind Rose with Calm Conditions (< 1 m/s)") plt.show() ``` -------------------------------- ### Visualize Wind Direction Frequency Source: https://github.com/python-windrose/windrose/blob/main/notebooks/usage.ipynb Generates a bar plot to visualize the frequency of wind directions. Requires matplotlib for plotting and accesses computed direction data from the windrose axes. ```python import matplotlib.pyplot as plt direction = ax._info["dir"] wd_freq = np.sum(table, axis=0) plt.bar(np.arange(16), wd_freq, align="center") xlabels = ( "N", "", "N-E", "", "E", "", "S-E", "", "S", "", "S-O", "", "O", "", "N-O", "", ) xticks = np.arange(16) plt.gca().set_xticks(xticks) plt.gca().set_xticklabels(xlabels) ``` -------------------------------- ### Create Monthly Wind Rose Subplots Source: https://context7.com/python-windrose/windrose/llms.txt Utilize Matplotlib subplots with the windrose projection to compare seasonal or monthly wind patterns. ```python import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from windrose import WindroseAxes # Generate monthly wind data np.random.seed(42) months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] fig = plt.figure(figsize=(16, 12)) fig.suptitle("Monthly Wind Patterns - 2024", fontsize=14) for i, month in enumerate(months, 1): # Simulate different wind patterns per month n = 200 # Vary predominant direction and speed by month base_dir = (i * 30) % 360 ws = np.random.weibull(2, n) * (5 + i * 0.5) wd = (np.random.normal(base_dir, 60, n)) % 360 ax = fig.add_subplot(3, 4, i, projection="windrose") ax.bar(wd, ws, bins=np.arange(0, 15, 3), normed=True, cmap=cm.viridis, opening=0.8) ax.set_title(month) plt.tight_layout() plt.show() ``` -------------------------------- ### bar(direction, var, **kwargs) Source: https://github.com/python-windrose/windrose/blob/main/docs/api.md Plots a windrose in bar mode. For each variable bin and each sector, a colored bar is drawn on the axes. ```APIDOC ## POST /windrose/bar ### Description Plots a windrose in bar mode. For each variable bin and each sector, a colored bar is drawn on the axes. ### Method POST ### Endpoint /windrose/bar ### Parameters #### Request Body - **direction** (1D array) - Required - Directions the wind blows from, North centered. - **var** (1D array) - Required - Values of the variable to compute. Typically the wind speeds. - **nsector** (integer) - Optional - Number of sectors used to compute the windrose table. Defaults to 16. - **sectoroffset** (float) - Optional - The offset for the sectors between [-180/nsector, 180/nsector]. Defaults to 0. - **bins** (1D array or integer) - Optional - Number of bins, or a sequence of bins variable. Defaults to 6. - **blowto** (bool) - Optional - If True, the windrose will be pi rotated to show where the wind blows to. - **colors** (string or tuple) - Optional - Color(s) for the bars. Can be a single string color or a tuple of matplotlib color arguments. - **cmap** (matplotlib.cm Colormap instance) - Optional - Colormap to use if colors is None. Defaults to a matplotlib default. - **edgecolor** (string) - Optional - The color of the edge of each bar. Defaults to no edgecolor. - **opening** (float) - Optional - Controls the space between each sector (1.0 for no space). Value between 0.0 and 1.0. - **calm_limit** (float) - Optional - Calm limit for the var parameter. Data below this value is removed from computation. If not None, a centered red circle is drawn for calm occurrences. ``` -------------------------------- ### windrose.wrscatter Source: https://github.com/python-windrose/windrose/blob/main/docs/api.md Draws a scatter plot for wind data. ```APIDOC ## windrose.wrscatter ### Description Draw scatter plot. ``` -------------------------------- ### Calculate Speed Histogram Source: https://github.com/python-windrose/windrose/blob/main/notebooks/windrose_sample_poitiers_csv.ipynb Computes the histogram of wind speeds based on defined bins. ```python data = np.histogram(df["speed"], bins=bins)[0] data ``` -------------------------------- ### Visualize Pollution Dispersion with Blowto Source: https://context7.com/python-windrose/windrose/llms.txt The blowto parameter rotates the wind rose by 180 degrees to represent the direction wind is blowing towards. ```python from windrose import WindroseAxes import numpy as np import matplotlib.pyplot as plt ws = np.random.weibull(2, 500) * 8 wd = np.random.random(500) * 360 fig, axes = plt.subplots(1, 2, figsize=(14, 6), subplot_kw={"projection": "windrose"}) # Standard wind rose (wind blows FROM) axes[0].bar(wd, ws, normed=True, bins=np.arange(0, 10, 2)) axes[0].set_legend() axes[0].set_title("Wind Blows FROM (Standard)") # Pollution rose (wind blows TO) axes[1].bar(wd, ws, normed=True, bins=np.arange(0, 10, 2), blowto=True) axes[1].set_legend() axes[1].set_title("Wind Blows TO (Pollution Rose)") plt.tight_layout() plt.show() ``` -------------------------------- ### Filled Windrose with Colormap Source: https://github.com/python-windrose/windrose/blob/main/notebooks/usage.ipynb Renders a filled windrose plot using a specified colormap (hot). Bin limits are defined using NumPy's arange. ```python from matplotlib import cm ax = WindroseAxes.from_ax() ax.contourf(wd, ws, bins=np.arange(0, 8, 1), cmap=cm.hot) ax.set_legend() ``` -------------------------------- ### windrose.wrcontourf Source: https://github.com/python-windrose/windrose/blob/main/docs/api.md Plots a windrose in filled mode. ```APIDOC ## windrose.wrcontourf ### Description Plot a windrose in filled mode. For each var bins, a line will be draw on the axes, a segment between each sector (center to center). ### Parameters - **direction** (1D array) - Required - directions the wind blows from, North centred - **var** (1D array) - Required - values of the variable to compute - **nsector** (integer) - Optional - number of sectors used to compute the windrose table - **bins** (1D array or integer) - Optional - number of bins, or a sequence of bins variable - **blowto** (bool) - Optional - If True, the windrose will be pi rotated - **colors** (string or tuple) - Optional - color configuration for bins - **cmap** (matplotlib.cm) - Optional - Colormap instance - **calm_limit** (float) - Optional - Calm limit for the var parameter - **kwargs** (others) - Optional - Any supported argument of matplotlib.pyplot.plot ``` -------------------------------- ### Create Windrose Subplots by Month Source: https://github.com/python-windrose/windrose/blob/main/notebooks/usage.ipynb Generates windrose plots as subplots, categorized by month, using Seaborn's FacetGrid. Requires `numpy`, `pandas`, `seaborn`, and `windrose`. ```python import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt from windrose import WindroseAxes, plot_windrose wind_data = pd.DataFrame( { "ws": np.random.random(1200) * 6, "wd": np.random.random(1200) * 360, "month": np.repeat(range(1, 13), 100), } ) def plot_windrose_subplots(data, *, direction, var, color=None, **kwargs): """wrapper function to create subplots per axis""" ax = plt.gca() ax = WindroseAxes.from_ax(ax=ax) plot_windrose(direction_or_df=data[direction], var=data[var], ax=ax, **kwargs) # this creates the raw subplot structure with a subplot per value in month. g = sns.FacetGrid( data=wind_data, # the column name for each level a subplot should be created col="month", # place a maximum of 3 plots per row col_wrap=3, subplot_kws={"projection": "windrose"}, sharex=False, sharey=False, despine=False, height=3.5, ) g.map_dataframe( plot_windrose_subplots, direction="wd", var="ws", normed=True, # manually set bins, so they match for each subplot bins=(0.1, 1, 2, 3, 4, 5), calm_limit=0.1, kind="bar", ) # make the subplots easier to compare, by having the same y-axis range y_ticks = range(0, 17, 4) for ax in g.axes: ax.set_legend( title=r"$m \cdot s^{-1}$", bbox_to_anchor=(1.15, -0.1), loc="lower right" ) ax.set_rgrids(y_ticks, y_ticks) # adjust the spacing between the subplots to have sufficient space between plots plt.subplots_adjust(wspace=-0.2) ``` -------------------------------- ### Generate Wind Rose Bar Plot Source: https://github.com/python-windrose/windrose/blob/main/notebooks/windrose_sample_poitiers_csv.ipynb Creates a wind rose bar plot using WindroseAxes. ```python import matplotlib.cm as cm from windrose import WindroseAxes ax = WindroseAxes.from_ax() ax.bar( df.direction.values, df.speed.values, bins=np.arange(0.01, 8, 1), cmap=cm.hot, lw=3 ) ax.set_legend(); ```