Plot multiple maps and data at the same time with Python's matplotlib

When doing research on earth and planetary science, I often come across a scene where I want to plot multiple maps and data on one figure at the same time. As a trial, this time, using Python's matplotlib,

--Plot monthly 2D data (global sea surface temperature data) from January to December into one figure at the same time with a map.

The goal is that.

1. Plot multiple maps at the same time

code

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.basemap import Basemap

xlim = [100, 170]			#Scope of the figure(x-axis direction: longitude)
ylim = [10, 60]				#Scope of the figure(y-axis direction: latitude)
column = 3					#Number of columns
fsizex, fsizey= 16, 18		#Horizontal / vertical length of the figure
line_interval = 15			#Spacing of parallels and meridians drawn on the map
fontsize = 20				#font size

if 12 % column != 0:
    raise ValueError('column must be a divisor of 12!')

row = 12 / column			#Number of rows
months =  [ 'Jan',  'Feb',  'Mar',  'Apr',
            'May',  'Jun',  'Jul',  'Aug',
            'Sep',  'Oct',  'Nov',  'Dec' ]

fig = plt.figure(figsize = (fsizex, fsizey))
plt.rcParams['font.size'] = fontsize

ax = [0] * 12
for i in range(0, 12):
    ax[i] = fig.add_subplot(row, column, 1 + i)
    m = Basemap(projection = 'cyl', llcrnrlat = ylim[0], urcrnrlat = ylim[1], \
                llcrnrlon = xlim[0], urcrnrlon = xlim[1], resolution = 'c', lon_0 = 180)
    m.drawcoastlines(linewidth = 0.5)
    m.drawmapboundary()
    m.fillcontinents(color = '#eeeeee')
    if i == 12 - column:
        label = [1, 1]
    elif i > 12 - column:
        label = [1, 0]
    elif i % column == 0:
        label = [0, 1]
    else:
        label = [0, 0]

    m.drawmeridians(np.arange(0, 360, line_interval), labels = [0, 0, 0, label[0]], linewidth = 0.5)
    m.drawparallels(np.arange(-90, 90, line_interval), labels = [label[1], 0, 0, 0], linewidth = 0.5)
    ax[i].set_xlim(xlim)
    ax[i].set_ylim(ylim)
    ax[i].set_title(months[i])

fig.tight_layout()
plt.show()

Figure

ダウンロード (12).png

2. Plot multiple maps and data at the same time

Preparation

If you are plotting 2D data for each month, combine each data for 12 months into a single 3D array.

xn = 360			#X-axis of data(longitude)Number of grids in the direction
yn = 155            #Y-axis of data(latitude)Number of grids in the direction
data = np.zeros((12, yn, xn))
for i in range(0, 12):
	data[i, :, :] = .....  # (i+1)Process to get month data

In addition, a one-dimensional array corresponding to the x-axis (longitude) and y-axis (latitude) of the two-dimensional data is acquired. This time, respectively

(Both are numpy.ndarray).

code

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.basemap import Basemap

xlim = [100, 170]			#Scope of the figure(x-axis direction: longitude)
ylim = [10, 60]				#Scope of the figure(y-axis direction: latitude)
column = 3					#Number of columns
fsizex, fsizey= 16, 18		#Horizontal / vertical length of the figure
cb_min, cb_max = -2, 32     #Minimum / maximum color bar
cb_div = 17					#Number of colors used in the color bar
clabel = 'Sea Surface Temperature(deg)' #Label attached to the color bar
line_interval = 15						#Spacing of parallels and meridians drawn on the map
fontsize = 20							#font size

if 12 % column != 0:
    raise ValueError('column must be a divisor of 12!')

row = 12 / column			#Number of rows
months =  [ 'Jan',  'Feb',  'Mar',  'Apr',
            'May',  'Jun',  'Jul',  'Aug',
            'Sep',  'Oct',  'Nov',  'Dec' ]

fig = plt.figure(figsize = (fsizex, fsizey))
plt.rcParams['font.size'] = fontsize

delta = (cb_max - cb_min) / cb_div
interval_of_cf = np.arange(cb_min, abs(cb_max) * 2 + delta, delta)[0:int(cb_div) + 1]

ax = [0] * 12
for i in range(0, 12):
    ax[i] = fig.add_subplot(row, column, 1 + i)
    m = Basemap(projection = 'cyl', llcrnrlat = ylim[0], urcrnrlat = ylim[1], \
                llcrnrlon = xlim[0], urcrnrlon = xlim[1], resolution = 'c', lon_0 = 180)
    m.drawcoastlines(linewidth = 0.5)
    m.drawmapboundary()
    m.fillcontinents(color = '#eeeeee')
    if i == 12 - column:
        label = [1, 1]
    elif i > 12 - column:
        label = [1, 0]
    elif i % column == 0:
        label = [0, 1]
    else:
        label = [0, 0]

    m.drawmeridians(np.arange(0, 360, line_interval), labels = [0, 0, 0, label[0]], linewidth = 0.5)
    m.drawparallels(np.arange(-90, 90, line_interval), labels = [label[1], 0, 0, 0], linewidth = 0.5)

    #Draw color contours
    x, y = np.meshgrid(xgrid, ygrid)
    X, Y = m(x, y)
    CF = ax[i].contourf(X, Y, data[i, :, :], interval_of_cf)

    ax[i].set_xlim(xlim)
    ax[i].set_ylim(ylim)
    ax[i].set_title(months[i])

#Draw a color bar
cax = fig.add_axes([1.00, 0.15, 0.04, 0.7])
cb = fig.colorbar(CF, cax)
cb.set_label(clabel)

fig.tight_layout()
plt.show()

Figure

ダウンロード (13).png

Succeeded in creating safely. The combination of vertical and horizontal can be freely changed by changing the value of column.

** Reference URL **

http://seesaawiki.jp/met-python/d/matplotlib/plot http://bicycle1885.hatenablog.com/entry/2014/02/14/023734 http://nm-player.blogspot.jp/2012/09/matplotlibbasemap-1.html http://qiita.com/AnchorBlues/items/0dd1499196670fdf1c46

Recommended Posts

Plot multiple maps and data at the same time with Python's matplotlib
I tried the same data analysis with kaggle notebook (python) and Power BI at the same time ②
I tried the same data analysis with kaggle notebook (python) and Power BI at the same time ①
Type conversion of multiple columns of pandas DataFrame with astype at the same time
Turn multiple lists with a for statement at the same time in Python
wxPython: Draw animation and graph drawing at the same time
Reformat the timeline of the pandas time series plot with matplotlib
Browse .loc and .iloc at the same time in pandas DataFrame
Plot CSV of time series data with unixtime value in Python (matplotlib)
Set up a server that processes multiple connections at the same time
Format and display time series data with different scales and units with Python or Matplotlib
I want to make a music player and file music at the same time
Implement "Data Visualization Design # 3" with pandas and matplotlib
Loop variables at the same time in the template
I just wanted to extract the data of the desired date and time with Django
Let's look at the scatter plot before data analysis
Get comments and subscribers with the YouTube Data API
Adjust the ratio of multiple figures with the matplotlib gridspec
3D plot with matplotlib
Time series plot / Matplotlib
I tried to automatically post to ChatWork at the time of deployment with fabric and ChatWork Api
How to register the same data multiple times with one input on the Django management screen
Steps to change table and column names in your Django model at the same time
Python built-in function ~ divmod ~ Let's get the quotient and remainder of division at the same time
[Python] Read the csv file and display the figure with matplotlib
[Introduction to matplotlib] Read the end time from COVID-19 data ♬
Graph time series data in Python using pandas and matplotlib
python memo: enumerate () -get index and element of list at the same time and turn for statement
Graph Excel data with matplotlib (1)
Graph Excel data with matplotlib (2)
Stackable bar plot with matplotlib
Animate multiple graphs with matplotlib
[Python 3.8 ~] Rewrite arrays etc. at the same time as definition [tips]
Install and manage multiple environments of the same distribution on WSL
When plotting time series data and getting a matplotlib Overflow Error
[Statistics] [Time series analysis] Plot the ARMA model and grasp the tendency.