瑞利散射 拉曼散射 米散射_使用Cartopy的时移散射图可视化

本文介绍了如何利用Python的Cartopy库创建时移散射图,以可视化瑞利、拉曼和米散射现象。通过这个可视化工具,可以更直观地理解这三种不同的散射过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

瑞利散射 拉曼散射 米散射

简介(我们将创建的内容): (Introduction (what we’ll create):)

Cartopy is your choice of library if you want to create static, non-interactive images/ videos of scatter map-visualizations using a custom background. The following video, which we’ll create in this tutorial, is a good example of what is possible with Cartopy:

如果要使用自定义背景创建散点图可视化的静态,非交互式图像/视频,则可以选择Cartopy。 我们将在本教程中创建的以下视频很好地说明了Cartopy的可能:

本教程的结构: (Structure of the tutorial:)

The tutorial is structured into the following sections:

本教程分为以下几节:

  1. Pre-requisites

    先决条件

  2. Installing Cartopy

    安装Cartopy

  3. Getting started with the tutorial

    教程入门

    Getting started with the tutorial

    教程入门

    -

    --

    Importing relevant packages

    导入相关包

    Importing relevant packages

    导入相关包

    -

    --

    Loading the data and making sense of it

    加载数据并使其有意义

    Loading the data and making sense of it

    加载数据并使其有意义

    -

    --

    Setting custom background

    设置自定义背景

    Setting custom background

    设置自定义背景

    -

    --

    Generating the plots

    生成图

    Generating the plots

    生成图

    -

    --

    Stitching the images to form a video

    拼接图像以形成视频

  4. When to use this library

    何时使用此库

先决条件: (Pre-requisites:)

This tutorial assumes that you are familiar with python and that you have python downloaded and installed in your machine. If you are not familiar with python but have some experience of programming in some other languages, you may still be able to follow this post, depending on your proficiency.

本教程假定您熟悉python,并且已在计算机中下载并安装了python。 如果您不熟悉python,但有一些使用其他语言进行编程的经验,则根据您的熟练程度,仍然可以继续阅读此文章。

安装Cartopy: (Installing Cartopy:)

If you are using Anaconda,

如果您正在使用Anaconda,

conda install -c conda-forge cartopy

Otherwise, the installation process is a bit lengthy. First, you need to install the following dependencies: GEOS, NumPy, Cython, Shapely, pyshp, and six. These can be installed using the pip installer or other package managers such as apt-get (Linux) and brew (macOS). Once these dependencies are installed, Cartopy can be installed using

否则,安装过程会很漫长。 首先,您需要安装以下依赖项: GEOSNumPyCythonShapelypyshp六个。 这些可以使用pip安装程序安装 或其他软件包管理器,例如apt-get(Linux)和brew(macOS)。 一旦安装了这些依赖项,就可以使用以下方法安装Cartopy

pip install cartopy

For more information on installing Cartopy, see https://scitools.org.uk/cartopy/docs/latest/installing.html

有关安装Cartopy的更多信息,请参见https://scitools.org.uk/cartopy/docs/latest/installing.html

教程入门 (Getting started with the tutorial)

Git repository: https://github.com/carnot-technologies/MapVisualizations

Git存储库: https : //github.com/carnot-technologies/MapVisualizations

Relevant notebook: CartopyDemo.ipynb

相关笔记本: CartopyDemo.ipynb

View notebook on NBViewer: Click Here

在NBViewer上查看笔记本: 单击此处

导入相关软件包: (Importing relevant packages:)

import numpy as np
from datetime import datetime, timedeltaimport matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy as cartopy
%matplotlib inlineimport os as os

加载数据并理解它: (Loading the data and making sense of it:)

The data set that we’ll be using is provided in the ‘data’ folder. Load the scatter_dummy_data.csv from that folder.

我们将使用的数据集位于“数据”文件夹中。 从该文件夹加载scatter_dummy_data.csv。

#Load the data
df = pd.read_csv('data\\scatter_dummy_data.csv')

On observing the contents of the dataframe, you’ll notice that it consists of the following columns:

在观察数据框的内容时,您会注意到它由以下几列组成:

  1. day (the day on which the trip happened)

    一天(旅行发生的当天)
  2. device_fk_id (the ID of your IoT device)

    device_fk_id(您的IoT设备的ID)
  3. n_trip_on (Number of trip ON points)

    n_trip_on(行程开启点数)
  4. start_lat (Latitude at the start of the trip)

    start_lat(行程开始时的纬度)
  5. start_lon (Longitude at the start of the trip)

    start_lon(行程开始时的经度)

One way of understanding this data is to use a ride-hailing service analogy. Suppose you have a ride-hailing service, like Uber, and you install an IoT device in each cab. This data represents the starting location for each trip and the number of points in each trip (a proxy for the duration of the trip), sent by each device every day.

理解此数据的一种方法是使用打车服务类比。 假设您拥有像Uber这样的乘车服务,并且在每个出租车中都安装了IoT设备。 该数据代表每个设备每天发送的每次行程的起始位置和每次行程的点数(行程持续时间的代理)。

We will attempt to see how the trip data changes in March, in the form of a time-lapse video. First, we’ll need to ensure that the type of the day column is datetime. For that, we explicitly convert it to datetime.

我们将尝试以延时视频的形式查看3月份的旅行数据如何变化。 首先,我们需要确保日期列的类型为日期时间。 为此,我们将其显式转换为日期时间。

#Convert the day column to datetime
df['day'] = pd.to_datetime(df['day'],format="%d-%m-%Y")

设置自定义背景: (Setting custom background:)

Now, before we begin plotting the points, we want to set a custom background. The ability to set a custom world-map image as a background is the USP of this library. By default, cartopy comes with just one default background, shown below. On a Windows machine, it can be found at the following address: C:\ProgramData\Anaconda3\Lib\site-packages\cartopy\data\raster\natural_earth

现在,在开始绘制点之前,我们要设置自定义背景。 将自定义世界地图图像设置为背景的功能是此库的USP。 默认情况下,cartopy仅带有一个默认背景,如下所示。 在Windows机器上,可以在以下地址找到它:C:\ ProgramData \ Anaconda3 \ Lib \ site-packages \ cartopy \ data \ raster \ natural_earth

Image for post
The default world map that comes along with the Cartopy library
Cartopy库随附的默认世界地图

However, this background doesn’t look very aesthetic. Instead, we will use a Blue Marble map from NASA. A lot of beautiful world maps can be found here: https://visibleearth.nasa.gov/collection/1484/blue-marble.

但是,这种背景看起来并不十分美观。 取而代之的是,我们将使用NASA的“蓝色大理石”地图。 在这里可以找到许多美丽的世界地图: https : //visibleearth.nasa.gov/collection/1484/blue-marble

The map that we’ll be using is shown below:

我们将使用的地图如下所示:

Image for post
Blue Marble NASA map that we’ll be using in this tutorial
我们将在本教程中使用的Blue Marble NASA地图

Now, in order to use this map, we need to tell Cartopy where to find it. That is accomplished by setting the ‘CARTOPY_USER_BACKGROUNDS’ environment variable.

现在,为了使用此地图,我们需要告诉Cartopy在哪里找到它。 这可以通过设置环境变量“ CARTOPY_USER_BACKGROUNDS”来完成。

#Set the directory for the background image
current_directory = os.getcwd()
os.environ["CARTOPY_USER_BACKGROUNDS"] = os.path.join(current_directory,'data','CARTOPY_IMGS')

If you check in the ‘data’ folder in your cloned repository, you will see a folder called ‘CARTOPY_IMGS’ containing the above Blue Marble image and an images.json file. The above piece of code assigns the path to this folder to the ‘CARTOPY_USER_BACKGROUNDS’ environment variable. In order to verify that the path has been set properly, you can query the path.

如果您在克隆的存储库中检入“数据”文件夹,则将看到一个名为“ CARTOPY_IMGS”的文件夹,其中包含上述Blue Marble图像和images.json文件。 上面的代码段将此文件夹的路径分配给环境变量“ CARTOPY_USER_BACKGROUNDS”。 为了验证路径是否已正确设置,您可以查询路径。

#Verify that the environment variable has been correctly set
os.getenv('CARTOPY_USER_BACKGROUNDS')

The images.json file contains the metadata of the images. If an image is physically present in the folder but not described in images.json, then Cartopy will throw up an error.

images.json文件包含图像的元数据。 如果图像实际上存在于文件夹中,但没有在images.json中描述,则Cartopy将抛出错误。

Our images.json file looks like the following:

我们的images.json文件如下所示:

{“__comment__”: “JSON file specifying the image to use for a given type/name and resolution. Read in by cartopy.mpl.geoaxes.read_user_background_images.”,
“BM_NASA”: {
“__projection__”: “PlateCarree”,
“__comment__”: “CustomBG”,
“__source__”: “CustomSource”,
“low”: “BM_NASA.png” }
}

BM_NASA is the name of the image. The value for the key ‘low’ indicates which image file to use if the user has asked for the low-resolution version. We could similarly have separate files for medium and high resolution for the same image. You can find out more about the background image in cartopy here.

BM_NASA是图像的名称。 键“ low”的值指示如果用户要求使用低分辨率版本,则使用哪个图像文件。 同样,对于同一张图像,我们可以为中分辨率和高分辨率使用单独的文件。 您可以在此处找到有关cartopy的背景图像的更多信息

生成图: (Generating the plots:)

Now that we have the background map, we’ll first limit its extent only to India.

现在我们有了背景图,我们首先将其范围仅限于印度。

#Define the extent of the plot. 
#Here the extreme lat lon of India are hard-coded.

lat_min = 8.06890
lat_max = 37.08586
lon_min = 68.1941
lon_max = 97.39564
extent = [lon_min, lon_max, lat_min, lat_max]
central_lon = np.mean(extent[:2])
central_lat = np.mean(extent[2:])

With both the background and the image set, we can now generate images for each day. The following snippet will generate 29 images, for data belonging to 1st to 29th of March, in the frames_cartopy folder:

有了背景和图像集,我们现在可以每天生成图像。 以下代码段将为frames_cartopy文件夹中的3月1日至29日的数据生成29张图像:

fig = plt.figure(figsize=(24, 12))
ax = plt.axes(projection=ccrs.PlateCarree(central_lon))for i in range(1,30):
date = datetime(2020,3,i)
df_single_day = df[df['day'] == date]
if ax is None:
fig = plt.figure(figsize=(24, 12))
ax = plt.axes(projection=ccrs.PlateCarree(central_lon))
ax.set_extent(extent, crs=ccrs.PlateCarree()) #Setting the background image and creating the plot
ax.background_img(name='BM_NASA',
resolution='low',
extent = extent)

ax.scatter(df_single_day['start_lon'],
df_single_day['start_lat'],
s=df_single_day['n_trip_on'].apply(lambda x: x/100),
alpha=0.8, color='#FFFF50',
transform=ccrs.PlateCarree())

#Adding text
fontsize = 36
# Positions for the date
date_x = 85
date_y = 10 ax.text(date_x, date_y,
f"{date.strftime('%b %d, %Y')}",
color='white',
fontsize=fontsize,
transform=ccrs.PlateCarree()) #saving the figure. Name the files as frame_01, frame_02, etc.
fig.savefig(f"frames_cartopy/frame_{i:02d}.png",
dpi=100,facecolor='black', bbox_inches='tight')

#Clear all the figures except the last one.
#We'll show the last one in-line in the notebook.
if(i != 29):
ax.clear()

While the comments in the above snippet make it self-explanatory, I’ll explain a couple of important lines.

尽管以上摘录中的注释不言自明,但我将解释一些重要的内容。

#Setting the background image and creating the plot
ax.background_img(name='BM_NASA',
resolution='low',
extent = extent)

ax.scatter(df_single_day['start_lon'],
df_single_day['start_lat'],
s=df_single_day['n_trip_on'].apply(lambda x: x/100),
alpha=0.8, color='#FFFF50',
transform=ccrs.PlateCarree())

Here, the ax.background_img reads the images.json file to determine which is the low-resolution version of the BM_NASA image. In the scatter plot, a scaled version of the ‘n_trip_on’ field has been used for setting the size of each individual scatter point. Thus, devices that did a longer trip will be represented by a larger circle.

在这里,ax.background_img读取images.json文件,以确定哪个是BM_NASA图像的低分辨率版本。 在散点图中,“ n_trip_on”字段的缩放版本已用于设置每个散点的大小。 因此,行程较长的设备将以较大的圆圈表示。

The next important field is the ‘transform’ field. PlateCarree is just one of the transforms possible with Cartopy. There are several others, like Orthographic, Mercator, etc. To get the list of all transforms, along with their interpretations, click here.

下一个重要字段是“转换”字段。 PlateCarree只是Cartopy可能进行的转换之一。 还有其他几种,如正交,墨卡托等。要获取所有变换的列表及其解释,请单击此处

Congratulations! You have created a separate visualization for each day! Now the last step is to stitch these images together to form a time-lapse video.

恭喜你! 您每天都创建了一个单独的可视化文件! 现在,最后一步是将这些图像拼接在一起以形成延时视频。

Image for post

拼接图像以形成视频: (Stitching the images to form a video:)

Now that we have the images prepared, we can now stitch them together to form our time-lapse video. For that open your terminal or command prompt, navigate to the frames_cartopy folder and run the following command:

现在我们已经准备好图像,现在可以将它们缝合在一起以形成延时视频。 为此,请打开终端或命令提示符,导航至frames_cartopy文件夹并运行以下命令:

ffmpeg -framerate 3 -i frame_%2d.png -c:v h264 -r 30 -s 1920x1080 ./cartopy_video.mp4

Here, we are using a frame rate of 3 frames per second. Our frames are named as frame_01.png, frame_02.png, up to frame_29.png. frame_%2d.png tells the command to look for files with two digits after ‘frame_’ and arrange them in the ascending order. The resolution is specified as 1920x1080 and the name of the video is cartopy_video.mp4.

在这里,我们使用每秒3帧的帧速率。 我们的框架分别命名为frame_01.png,frame_02.png和up_frame_29.png。 frame_%2d.png告诉命令查找“ frame_”后两位数字的文件,并按升序排列。 分辨率指定为1920x1080,视频名称为cartopy_video.mp4。

To know more about the different options related to video-encoding using ffmpeg, you can visit https://trac.ffmpeg.org/wiki/Slideshow

要了解有关使用ffmpeg进行视频编码的不同选项的更多信息,请访问https://trac.ffmpeg.org/wiki/Slideshow

何时使用此库: (When to use this library:)

This library comes in handy when you want to create an image/ video with a custom background. It can be used for static images/videos that you want to include in presentations or websites. However, there is absolutely no interactivity that you can get with this library. If you want to host a visualization wherein people can zoom into the map/ click on the points, this is not the choice of library for you. You would want to use a library like plotly for that purpose.

当您要创建具有自定义背景的图像/视频时,此库非常有用。 它可用于要包含在演示文稿或网站中的静态图像/视频。 但是,使用此库绝对无法获得交互性。 如果您想托管一个可视化视图,使人们可以放大地图/单击这些点,那么这不是您要选择的库。 为此,您可能希望使用像plotly这样的库。

We are trying to fix some broken benches in the Indian agriculture ecosystem through technology, to improve farmers’ income. If you share the same passion join us in the pursuit, or simply drop us a line on report@carnot.co.in

我们正在尝试通过技术修复印度农业生态系统中一些破烂的长凳 ,以提高农民的收入。 如果您有同样的热情,请加入我们的行列或者直接给我们写信至report@carnot.co.in

翻译自: https://medium.com/tech-carnot/time-lapse-scatter-map-visualization-using-cartopy-9b7b88ef8b6b

瑞利散射 拉曼散射 米散射

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值