Basic Plotting with Matplotlib (Scatterplot, Barplot, Heatmap, Boxplot, etc.) Cartopy and Map plotting Plotting Contourplot using Precipitation data Choosing colorbars Wind direction (u and v) Making a Skew-T with wind barbs using MetPy Color maps in Matplotlib and creating customized color bar Interactive plotting
Suggestions 23 june
Matplotlib is a Python library for creating high-quality visualizations and plots of data.It is the most well-known of all the python visualization packages and provides a variety of capabilities such as:
Matplotlib can gernerate high-quality graphics in a number of file types including PDF, SVF, JPG, PNG, BMP and GIF.
Matplotlib include line plots, scatter plots, histograms, bar charts, pie charts, and box plots.
Additionally, it enables 3D charting, and many additional libraries, such as pandas and Seaborn, have been built on top of it to provide access to Matplotlib's capabilities with less code.
Let's have a look at some of the basic function that are often used in matplotlib.
Function | Description |
---|---|
plt.plot() | Creates line plots to represent data. |
plt.scatter() | Generates scatter plots to display individual data points. |
plt.bar() | Creates bar plots to visualize categorical data. |
plt.hist() | Generates histograms to display the distribution of numerical data. |
plt.boxplot() | Creates boxplots to show the distribution and outliers of a dataset. |
plt.pie() | Generates pie charts to display proportions or percentages of categorical data. |
plt.imshow() | Displays images or heatmaps using arrays of data. |
plt.show() | it displays the created plots |
plt.xlabel() | This function is used to add a label to the x-axis of the plot. |
plt.ylabel() | This function is used to add a label to the y-axis of the plot. |
plt.title() | This function is used to add a title to the plot. |
plt.legend() | Adds a legend to the plot to identify plotted elements. |
plt.xticks() | This function is used to set the tick locations and labels for the x-axis. |
plt.yticks() | This function is used to set the tick locations and labels for the y-axis. |
plt.grid() | This function is used to add a grid to the plot. |
plt.xlim() | Sets the limits for the x-axis. |
plt.ylim() | Sets the limits for the y-axis. |
plt.annotate() | it is use to write comments on the graph at the specified position |
plt.figure(figsize = (x, y)) | whenever we want the result to be displayed in a separate window we use this command, and figsize argument decides what will be the initial size of the window that will be displayed after the run |
plt.subplot(r, c, i) | it is used to create multiple plots in the same figure with r signifies the no of rows in the figure, c signifies no of columns in a figure and i specifies the positioning of the particular plot |
These are some common functions used in matplotlib plotting.
To use matplotlib we need to import it.We will use standard shorthand for matplotlib imports to make things simpler.
import matplotlib.pyplot as plt
Here we have imported the pyplot
module from the matplotlib
library as plt
.This is a common convention to simplify the usage of pyplot
functions throughout the code.
Basically, we'll be using **`plt`** instead of **`matplotlib.pyplot`**
Step by step guide to create a scatterplot:
**Step 1:**
Firstly, we'll import the necessary packages.We'll use matplotlib
for plotting and numpy
to produce data.
**Step 2:**
Then we'll gernerate random data using numpy to plot.Here,we'll use Numpy's random.normal()
function to generate 100 random numbers for two variables:x
and y
**Step 3:**
In this step we'll plot the data using matplotlib's scatter()
function to create a scatter plot of the x
and y
data points.
Syntax of scatterplot :
matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, *, edgecolors=None, plotnonfinite=False, data=None, **kwargs)
**Step 4:** Finally, we use the show()
function to display the plot.
# import packages
import matplotlib.pyplot as plt
import numpy as np
# generate random data
x = np.random.normal(size=100)
y = np.random.normal(size=100)
# plot the data
plt.scatter(x, y)
# show the plot
plt.show()
Step by step guide to create a scatterplot:
**Step 1:** Firstly, we'll import the necessary packages.We'll use matplotlib
for plotting and numpy
to produce data.
**Step 2:**Then we'll gernerate random data using numpy to plot.Here,we'll use Numpy's NumPy's random.randint()
function to generate a list of 8 random integers between 1 and 150.
**Step 3:** In this step we'll use the bar()
function from pyplot to create a bar graph. The range(len(data))
is used to generate a sequence of indices corresponding to each data point, and data
represents the height of each bar. The color
parameter is set to '#900C3F' to specify the color of the bars.
Syntax of bar plot:
matplotlib.pyplot.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)
**Step 4:**Finally, we use the show()
function to display the plot.
#Importing packages
import matplotlib.pyplot as plt
import numpy as np
#Creating random list of 8 numbers.
data = list(np.random.randint(1, 150, 8))
#Plotting the horizontal bar.
plt.bar(range(len(data)), data, color='#900C3F')
#showing the plot
plt.show()
#Importing packages
import matplotlib.pyplot as plt
import numpy as np
#Creating random list of 8 numbers.
data = list(np.random.randint(1, 150, 8))
#Plotting the horizontal bar.
plt.barh(range(len(data)), data, color='#900C3F')
#showing the plot
plt.show()
A heatmap is a graphical representation of data where values are represented as colors in a two-dimensional grid. Heatmaps are particularly useful for visualizing patterns, correlations, or distributions in data matrices.
Let's see a heatmap
**Explanation:**
Here we see a heatmap representing the harvest data of local farmers. Each cell in the heatmap corresponds to a combination of a vegetable and a farmer, with the color intensity representing the harvest amount. The color intensity of each cell gives us the values of harvest with help of color bar included.
Step by step guide to create heatmap:
**Step 1:** Firstly, we'll import the necessary packages.We'll use matplotlib
for plotting and numpy
to produce data.
**Step 2:**Then we'll gernerate random data using numpy to plot.Here,we'll use Numpy's NumPy's np.random.rand()
function to generate a 10x10 random matrix.
**Step 3:** In this step we'll use the imshow()
function from pyplot to create a heatmap.The data
matrix is used as the input data. The cmap
parameter is set to autumn
to use the autumn color map.
Syntax of Heat map:
matplotlib.pyplot.imshow(X, cmap=None, alpha=None)
X :- this is input data matrix which is to be displayed
cmap :- Colormap we use t0 dispay the heatmap
alpha :- it specifies the opacity or transpiracy of the heatmap
**Step 4:** a color bar is then added.
**Step 5:**we set the title and labels.
**Step 6:**Finally, we use the show()
function to display the plot.
import matplotlib.pyplot as plt
import numpy as np
# Generate random data
data = np.random.rand(10, 10) # Generate a 10x10 random matrix
# Create a heatmap
plt.imshow(data, cmap='autumn')
# Add a color bar
plt.colorbar()
# Set title and labels
plt.title('Heatmap Example')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Show the plot
plt.show()
A boxplot also known as a box and whisker plot is a graphical representation of the distribution of a dataset.
It has the following component:
**Box:** The box represents the interquartile range (IQR), which contains the middle 50% of the data. The bottom edge of the box represents the 25th percentile (lower quartile), while the top edge represents the 75th percentile (upper quartile). The line inside the box represents the Median.
**Whiskers:** The whiskers extend from the box to the minimum and maximum non-outlier data points. They give an idea of the range of the dataset, excluding any outliers.
**Outliers:** Individual data points that are considered outliers are plotted as individual points outside the whiskers. They are typically defined as points that fall outside a certain multiple of the IQR from the edges of the box.By default, the range is set to 1.5 times the IQR.
Step by step guide to create a boxplot:
**Step 1:** Firstly, we'll import the necessary packages.We'll use matplotlib
for plotting and numpy
to produce data.
**Step 2:**Then we'll gernerate random dataset using numpy to plot.Here,we'll use Numpy's NumPy's random.normal()
function where the loc
parameter specifies the mean of the distribution, which is set to 0 in this case. The scale
parameter specifies the standard deviation of the distribution, which is set to 1. The size
parameter determines the number of data points in the dataset, which is set to 100.Then we added some outliers to data and created the final data.
**Step 3:** In this step we'll use the boxplot()
function from pyplot. The data
array is passed as the argument, which contains the dataset to be visualized.
Syntax of boxplot:
matplotlib.pyplot.boxplot(x, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=None, bootstrap=None, usermedians=None, conf_intervals=None, meanline=None, showmeans=None, showcaps=None, showbox=None, showfliers=None, boxprops=None, labels=None, flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None, manage_ticks=True, autorange=False, zorder=None, capwidths=None, *, data=None)
**Step 4:**We add title and labels.
**Step 5:**Finally, we use the show()
function to display the plot.
import matplotlib.pyplot as plt
import numpy as np
# Generating random data
data = np.random.normal(loc=0, scale=1, size=100)
# Adding outliers
outliers = np.array([-3, 3]) # Example outliers
# Final data
data_with_outliers = np.concatenate((data, outliers))
# Create a boxplot
plt.boxplot(data_with_outliers)
# Set title and labels
plt.title('Boxplot Example')
plt.xlabel('Data')
# Show the plot
plt.show()
Cartopy is a Python package designed for geospatial data processing in order to make it easier to work with and analyze data that is related to the Earth's surface. It is built on top of several other popular scientific Python packages such as NumPy, Matplotlib, and Shapely, and provides a way to create maps, plot data on maps, and perform various geographical data analysis tasks.
Please note that when using cartopy in colab, it may sometimes crash. To avoid errors, please run the following cell. You can ignore the contents of the cell, and simply copy and paste the code whenever you need to use cartopy. After successfully installing all necessary components, please restart the runtime.
Runtime --> Restart Runtime --> do not run again after restart
# Run this cell when you are in colab and then restart runtime
# Do not worry about this cell, you can always copy paste
!apt-get install libproj-dev proj-data proj-bin
!apt-get install libgeos-dev
!pip install cython
!pip install cartopy
!apt-get -qq install python-cartopy python3-cartopy
!pip uninstall -y shapely # cartopy and shapely aren't friends (early 2020)
!pip install shapely --no-binary shapely
# importing libraries
import warnings
warnings. filterwarnings("ignore")
import matplotlib.pyplot as plt
# importing cartopy
import cartopy.feature as cf
import cartopy.crs as ccrs
import cartopy.mpl.ticker as cticker
from cartopy.util import add_cyclic_point
Let's start by creating a basic map using cartopy. To do this, we first need to define an axes
and a projection
. Once the projection is defined, we can add coastlines to the map, specifying the linewidth and color. We'll delve deeper into projections
later on.
map = plt.axes(projection=ccrs.PlateCarree()) # defining axes and projection* and assigned it to `map`
map.coastlines() # add coastlines
We add features by calling the add_feature()
method on-axis object and passing a feature object available from the cartopy.feature
module.
We can add the following features (part of cartopy.feature
) to our map:
COASTLINE
: Adds coastline around all continents.LAND
: Adds land on top of world map.LAKES
: Adds big lakes of the world.BORDERS
: Adds country borders for the whole world.OCEAN
: Adds ocean with a color.RIVERS
: Adds big rivers of the world.# Adding more features and add stock images
plt.figure(figsize=(12,12))
map4 = plt.axes(projection=ccrs.PlateCarree())
map4.add_feature(cf.LAND)
map4.add_feature(cf.OCEAN)
map4.add_feature(cf.COASTLINE)
map4.add_feature(cf.BORDERS, linestyle=':')
map4.add_feature(cf.LAKES, alpha=0.5)
map4.add_feature(cf.RIVERS)
map4.stock_img() # try comment this
Need to provide the longitude and latitude ranges as arguments of the set_extent
method on the axes object:
ax.set_extent([min_lon, max_lon, min_lat, max_lat])
# Cropping the map with set_extent
plt.figure(figsize=(12,12))
map5 = plt.axes(projection=ccrs.PlateCarree())
map5.add_feature(cf.LAND)
map5.add_feature(cf.OCEAN)
map5.add_feature(cf.COASTLINE)
map5.add_feature(cf.BORDERS, color='k') # you can also change color, linewidth etc
map5.add_feature(cf.LAKES, alpha=0.5)
map5.add_feature(cf.RIVERS)
map5.set_extent([87.5, 93, 20, 27]) # define the boundary
# Do not worry about this cell, you will almost never need it
fig = plt.figure(figsize=(13, 14))
fig.suptitle('Different Types of Projections', fontsize=20, y=0.92)
projections = {'PlateCarree': ccrs.PlateCarree(), 'AlbersEqualArea': ccrs.AlbersEqualArea(),
'AzimuthalEquidistant': ccrs.AzimuthalEquidistant(), 'EquidistantConic': ccrs.EquidistantConic(),
'LambertConformal': ccrs.LambertConformal(), 'LambertCylindrical': ccrs.LambertCylindrical(),
'Mercator': ccrs.Mercator(), 'Miller': ccrs.Miller(), 'Mollweide': ccrs.Mollweide(),
'Orthographic': ccrs.Orthographic(), 'Robinson': ccrs.Robinson(), 'Sinusoidal': ccrs.Sinusoidal(),
'Stereographic': ccrs.Stereographic(), 'TransverseMercator': ccrs.TransverseMercator(),
'InterruptedGoodeHomolosine': ccrs.InterruptedGoodeHomolosine(),
'RotatedPole': ccrs.RotatedPole(), 'OSGB': ccrs.OSGB(), 'EuroPP': ccrs.EuroPP(),
'Geostationary': ccrs.Geostationary(), 'NearsidePerspective': ccrs.NearsidePerspective(),
'EckertI': ccrs.EckertI(), 'EckertII': ccrs.EckertII(), 'EckertIII': ccrs.EckertIII(),
'EckertIV': ccrs.EckertIV(), 'EckertV': ccrs.EckertV(), 'EckertVI': ccrs.EckertVI(),
'Gnomonic': ccrs.Gnomonic(),
'LambertAzimuthalEqualArea': ccrs.LambertAzimuthalEqualArea(),
'NorthPolarStereo': ccrs.NorthPolarStereo(), 'OSNI': ccrs.OSNI(),
'SouthPolarStereo': ccrs.SouthPolarStereo()}
for index, projection in enumerate(projections.items()):
ax = fig.add_subplot(7, 5, index+1, projection=projection[1])
ax.coastlines()
ax.set_title(projection[0])
from google.colab import drive
drive.mount('/content/drive')
# Load the precipitation and temperature data from NetCDF files
data = xr.open_dataset("/content/drive/MyDrive/DataSets/ERA5_monthly_global_precipitation_temp.nc").load()
data
temperature = data['t2m']
yearly_temp = temperature.mean(dim='time')
# Create a Cartopy Mercator projection
projection = ccrs.Robinson()
# Create the figure and axis
plt.figure(figsize=(16,8))
ax = plt.axes(projection=ccrs.Robinson())
# Add map features
ax.add_feature(cf.COASTLINE, linewidth=0.2)
ax.add_feature(cf.BORDERS, linewidth=0.2)
ax.add_feature(cf.RIVERS)
ax.gridlines(draw_labels=True, linewidth=0.3)
# Plot the contour map of annual precipitation
cs = ax.contourf(data['longitude'], data['latitude'], (yearly_temp - 273.15), np.linspace(-55, 55, 23),cmap='coolwarm' , transform=ccrs.PlateCarree())
# Add a colorbar
cbar = plt.colorbar(cs, ax=ax, orientation='vertical', pad=0.05)
cbar.set_label('$Temperature {^\circ}C$')
# Set the plot title
plt.title('Mean temperature of year 2022')
# Show the plot
plt.show()
Now, its time to plot a real climate data with everything you learned earlier. For this, we use 2022 Precipitation data over Bangladesh and its sorrounding region.
The following cell will first uninstall some libraries and then reinstall the specified version.
last two line will clear the output screen.
!pip uninstall -y shapely
!pip uninstall -y importlib-metadata
!pip install shapely==1.7.1 --no-binary shapely
!pip install importlib-metadata==4.13.0
!pip install cartopy==0.21
from google.colab import output
output.clear()
After installing new python libraries, runtime needs to be restared. You can do it maually or run the following cell to kill this runtime. Then run the next cell, that will automatically connect the runtime and run.
import os
os.kill(os.getpid(), 9)
import numpy as np
import xarray as xr
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cf
import calendar
import requests
We specify the URL in the file_url variable.
Next, we make a request to the URL using requests.get(). The response object contains the content of the file.
We then open a file in binary write mode ("wb") at the desired location ("/content/data.nc") and write the content of the response into it.
Finally, we use xr.open_dataset() from xarray to open the downloaded file and load it into the data variable. You can replace "/content/data.nc" with your desired file path.
After executing this code, we have the data loaded into the data variable, and proceed with further analysis or operations using xarray.
file_url = "https://drive.google.com/uc?id=1Q5mzA7aDhRA2baMLZ71eio-ZFHQ3mGNN&export=download"
file_path = "/content/data.nc"
response = requests.get(file_url)
with open(file_path, "wb") as f:
f.write(response.content)
data = xr.open_dataset(file_path).load()
data
Extracting precipitation data for a whole year: In this step, the code extracts the precipitation data from the loaded dataset. It multiplies the 'tp' variable by 1000 to convert the unit from meters to millimeters. The longitude and latitude values are also extracted from the dataset.
Converting hourly data to daily data: Here, the code resamples the precipitation data from hourly to daily frequency using the .resample() method with a time frequency of '1D'. It then calculates the sum of precipitation for each day using the .sum() method.
Calculating the seasonal spatial distribution: Here, the code defines a list of season names (seasons) and a corresponding list of lists (season_months) containing the month indices for each season. The months are grouped as Winter (DJF: December, January, February), Pre-monsoon (MAM: March, April, May), Monsoon (JJA: June, July, August), and Post-monsoon (SON: September, October, November).
Calculating the seasonal mean precipitation: This code snippet calculates the mean precipitation for each season. It iterates over the season_months list, selects the corresponding data from daily_precipitation using .sel() and the isin() method to match the months, and then calculates the mean along the time dimension (dim='time') using .mean(). The seasonal mean precipitation values are stored in the seasonal_means list.
These operations help extract the precipitation data for a whole year, convert it to daily data, and calculate the seasonal mean precipitation for each predefined season.
# Extract the precipitation data for a whole year
precipitation = data['tp'] * 1000
lon = data['longitude']
lat = data['latitude']
# Convert hourly data to daily data
daily_precipitation = precipitation.resample(time='1D').sum()
# Seasonal Spatial Distribution
seasons = ['Winter (DJF)', 'Pre-monsoon (MAM)', 'Monsoon (JJA)', 'Post-monsoon (SON)'] # Winter, Spring, Summer, Autumn
season_months = [[12, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
# Calculate the seasonal mean precipitation
seasonal_means = []
for months in season_months:
seasonal_data = daily_precipitation.sel(time=daily_precipitation['time.month'].isin(months))
seasonal_mean = seasonal_data.mean(dim='time')
seasonal_means.append(seasonal_mean)
This code generates a 2x2 grid of subplots, where each subplot represents the seasonal spatial distribution of precipitation. Let's break it down step by step:
Create the subplots: The plt.subplots() function is used to create a figure with a grid of subplots. The nrows=2, ncols=2 arguments specify a 2x2 grid, and figsize=(12, 12) sets the size of the figure. The subplot_kw parameter sets the projection to ccrs.PlateCarree(), which is a map projection for visualizing global data.
Plot each seasonal mean precipitation: Using a loop, each subplot is accessed individually (ax). The contourf() function is used to plot the seasonal mean precipitation data (seasonal_means[i]) on each subplot. Additional features such as coastlines, borders, ocean, lakes, land, and rivers are added using add_feature(). The map extent is set using set_extent(min_lon, max_lon, min_lat, max_lat), and gridlines are drawn with gridlines().
Add colorbar and subplot titles: A vertical colorbar is added to each subplot using colorbar(). Subplot titles (seasons[i]) are set using set_title(). The colorbar ticks and label font sizes are customized.
Set the figure title and adjust layout: The overall figure title is set using suptitle(). The layout is adjusted using tight_layout() to optimize spacing between subplots.
Display the plot: Finally, plt.show() is called to display the plot.
Executing this code will generate a figure with four subplots, each showing the seasonal spatial distribution of precipitation. The color of the contourf plot represents the precipitation amount, and the colorbar provides a reference for the precipitation values in millimeters per day.
# Create the subplots
fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(12, 12),
subplot_kw={'projection': ccrs.PlateCarree()})
# Plot each seasonal mean precipitation on the subplots
for i, ax in enumerate(axs.flat):
cs = ax.contourf(lon, lat, seasonal_means[i], 30, extend='both', transform=ccrs.PlateCarree())
ax.add_feature(cf.COASTLINE)
ax.add_feature(cf.BORDERS, linewidth=1)
ax.add_feature(cf.OCEAN)
ax.add_feature(cf.LAKES)
ax.add_feature(cf.LAND)
ax.add_feature(cf.RIVERS)
ax.set_extent([87, 94, 20, 28])
bx = ax.gridlines(draw_labels=True, linewidth=0.2)
ax.set_title(seasons[i], fontsize=12, pad=10, y=1.04, loc="left")
# Add vertical colorbar to each subplot with a custom size
cbar = plt.colorbar(cs, ax=ax, orientation='vertical', pad=0.1, shrink=0.8)
cbar.ax.tick_params(labelsize=10)
cbar.ax.set_title('mm/day', fontsize=10)
# Add a title to the figure
fig.suptitle('Seasonal Spatial Distribution of Precipitation', fontsize=20, fontweight='bold')
# Adjust the spacing between subplots and display the plot
plt.tight_layout()
plt.show()
This code calculates the monthly total precipitation, calculates the mean precipitation for each month, and plots the temporal distribution of precipitation. Let's break it down step by step:
Calculate the monthly total precipitation: The resample() method with time='1M' is used to resample the daily precipitation data (daily_precipitation) to monthly frequency. The sum(dim='time') method then calculates the sum of precipitation for each month. The result is stored in the monthly_precipitation variable.
Calculate the mean precipitation for each month: Using NumPy, the np.mean() function is applied twice to calculate the mean precipitation. The first mean() call computes the mean along the latitude axis (axis=2), and the second mean() call computes the mean along the longitude axis (axis=1). The result is stored in the mean_monthly_precipitation variable.
Get the month labels: A list comprehension is used to extract the month labels from the monthly_precipitation['time'] values. Each value is converted to a string, split at the hyphen ('-'), and the second part (the month) is selected. The result is stored in the months variable.
Plot the temporal distribution of precipitation: A figure with a size of (10, 6) is created using plt.figure(figsize=(10, 6)). The plot() function is then used to plot the mean monthly precipitation (mean_monthly_precipitation) against the month labels (months). The marker style is set to 'o', the linestyle is set to '-', and the color is set to 'blue'. The x-axis label is set to 'Month', the y-axis label is set to 'Precipitation (mm)', and the title is set to 'Monthly Temporal Distribution of Precipitation'. Gridlines are enabled using plt.grid(True), and the x-axis tick labels are rotated by 45 degrees using plt.xticks(rotation=45). The layout is adjusted using plt.tight_layout().
Executing this code will calculate the monthly total precipitation, compute the mean precipitation for each month, and plot the temporal distribution of precipitation. The resulting plot will show the variation of precipitation over the months, providing insights into the seasonal patterns of precipitation.
# Calculate the monthly total precipitation
monthly_precipitation = daily_precipitation.resample(time='1M').sum(dim='time')
#Calculate the mean precipitation for each month
mean_monthly_precipitation = np.mean(np.mean(monthly_precipitation, axis=2), axis=1)
# Get the month labels
months = [str(month).split('-')[1] for month in monthly_precipitation['time'].values]
# Plot the temporal distribution of precipitation
plt.figure(figsize=(10, 6))
plt.plot(months, mean_monthly_precipitation, marker='o', linestyle='-', color='blue')
plt.xlabel('Month')
plt.ylabel('Precipitation (mm)')
plt.title('Monthly Temporal Distribution of Precipitation')
plt.grid(True)
plt.xticks(rotation=45)
plt.show()
Colormaps are extremely useful tool for plotting scientic data.They are used to make visualization look more appealing as well as self explanatory.
import matplotlib.pyplot as plt
import numpy as np
# Generate random data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create a sequential color map
cmap = 'viridis'
# Plot the data using the color map
plt.scatter(x, y, c=y, cmap=cmap)
# Add a color bar
plt.colorbar()
# Set title and labels
plt.title('Sequential Color Map Example')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Show the plot
plt.show()
import matplotlib.pyplot as plt
import numpy as np
# Generate random data
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)
# Create a diverging color map
cmap = 'RdBu'
# Plot the data using the color map
plt.contourf(X, Y, Z, cmap=cmap)
# Add a color bar
plt.colorbar()
# Set title and labels
plt.title('Diverging Color Map Example')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Show the plot
plt.show()
import matplotlib.pyplot as plt
import numpy as np
# Generate random data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create a qualitative color map
cmap = 'Set3'
# Plot the data using the color map
plt.scatter(x, y, c=y, cmap=cmap)
# Add a color bar
plt.colorbar()
# Set title and labels
plt.title('Qualitative Color Map Example')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Show the plot
plt.show()
file_url = "https://drive.google.com/uc?id=1Q5mzA7aDhRA2baMLZ71eio-ZFHQ3mGNN&export=download"
file_path = "/content/data.nc"
response = requests.get(file_url)
with open(file_path, "wb") as f:
f.write(response.content)
data = xr.open_dataset(file_path).load()
data
This following cell calculates the seasonal mean U and V wind components by converting the original hourly data to daily resolution and then averaging them over the specified seasons. The resulting seasonal means are stored in seasonal_means_u and seasonal_means_v lists.
Extracting U and V wind components for a whole year:
Converting hourly data to daily data:
Defining seasons and corresponding months:
Calculating the seasonal mean wind components:
# Extract the U and V wind components for a whole year
u_component = data['u10']
v_component = data['v10']
lon = data['longitude']
lat = data['latitude']
# Convert hourly data to daily data
u_daily = u_component.resample(time='1D').mean()
v_daily = v_component.resample(time='1D').mean()
# Seasonal Spatial Distribution
seasons = ['Winter (DJF)', 'Pre-monsoon (MAM)', 'Monsoon (JJA)', 'Post-monsoon (SON)'] # Winter, Spring, Summer, Autumn
season_months = [[12, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
# Calculate the seasonal mean wind components
seasonal_means_u = []
seasonal_means_v = []
for months in season_months:
seasonal_data_u = u_daily.sel(time=u_daily['time.month'].isin(months))
seasonal_data_v = v_daily.sel(time=v_daily['time.month'].isin(months))
seasonal_mean_u = seasonal_data_u.mean(dim='time')
seasonal_mean_v = seasonal_data_v.mean(dim='time')
seasonal_means_u.append(seasonal_mean_u)
seasonal_means_v.append(seasonal_mean_v)
This code creates a 2x2 grid of subplots, where each subplot represents the seasonal spatial distribution of the wind components. Wind vectors are plotted using quiver plots, and a quiver key is added to indicate the wind speed scale. Various cartopy features are added to enhance the visual representation.
Creating subplots:
Plotting each seasonal mean wind component:
Adding a title and adjusting layout:
Displaying the plot:
# Create the subplots
fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(12, 12),
subplot_kw={'projection': ccrs.PlateCarree()})
# Plot each seasonal mean wind component on the subplots
for i, ax in enumerate(axs.flat):
u_wind = seasonal_means_u[i]
v_wind = seasonal_means_v[i]
speed = np.sqrt(u_wind**2 + v_wind**2)
# Quiver plot of wind vectors
q = ax.quiver(lon, lat, u_wind, v_wind, speed, transform=ccrs.PlateCarree(), cmap='cool', width=0.003)
ax.add_feature(cf.COASTLINE)
ax.add_feature(cf.BORDERS, linewidth=1)
ax.add_feature(cf.OCEAN)
ax.add_feature(cf.LAKES)
ax.add_feature(cf.LAND)
ax.add_feature(cf.RIVERS)
ax.set_extent([87, 94, 20, 28])
bx = ax.gridlines(draw_labels=True, linewidth=0.2)
ax.set_title(seasons[i], fontsize=12, pad=10, y=1.04, loc="left")
# Add quiver key to each subplot
quiver_key = ax.quiverkey(q, 0.9, 1.06, 5, r'5 ${ms^{-1}}$', labelpos='E', coordinates='axes')
# Add a title to the figure
fig.suptitle('Seasonal Spatial Distribution of Wind Components', fontsize=20, fontweight='bold')
# Adjust the spacing between subplots and display the plot
plt.tight_layout()
plt.show()