Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python to draw cool vehicle tracks

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article focuses on "how to use Python to draw cool vehicle tracks", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use Python to draw cool vehicle tracks.

The origin of the problem

Recently I came across a kind of graph, which is very good-looking, and has been encountered many times in other papers. For example, figure 1 in the article Trajectory data-based traffic flow studies: a revisit, as shown in the following figure:

Due to the length of the original picture, only part of the picture is referenced here. Several key messages can be clearly seen from the above picture:

The horizontal axis represents the time change, indicating that the data needs to be time series.

The longitudinal axis represents the spatial position, which can be understood as the distance traveled by the vehicle after leaving the section of a road.

Each track represents a change in the driving path of a car, while the color of the line represents the instantaneous speed value.

Therefore, if you want to draw the image above, you need a data set with information about the instantaneous trajectory, speed, time and so on of the vehicle.

two。 Prepare data

In order to try to draw the image, you now need to do two things. First, find the right data; second, find a convenient drawing tool.

Basic data

For the NGSIM data set, make a brief introduction 2: it contains the vehicle track data of four road sections, any one of which is recorded by setting a high-definition camera on the surrounding high-rise buildings of the road section, and then through image processing, the track changes of each vehicle are collected, and then the lane, instantaneous speed, instantaneous acceleration, instantaneous headway and so on can be calculated.

As the key information related to this drawing, we only need to know the following data:

As a demonstration, you can use data from only one lane.

The instantaneous speed information in the middle of each car from entering the camera area to leaving, the corresponding data label in NGSIM is v_Vel.

The coordinates in the middle of each car change from entering the camera area to leaving. The corresponding data labels in NGSIM are Local_X and Local_Y.

At the corresponding moment, the corresponding data label in NGSIM is Global_Time

Well, once you know the above three key data, you can use the drawing tool to draw.

Drawing tool

Considering the repeatability, portability and convenience, the Matplotlib package in Python is used to draw.

3. Start drawing

Before you start drawing, you need to have the following three packages configured in the Python environment:

Pandas, the main function of this article is to read and process data.

Numpy, this article is mainly used for scientific computing.

Matplotlib, this article is mainly used for drawing

Import the necessary packages

There is no doubt that these packages will be used, so let's import them into the program first:

Import pandas as pdimport numpy as npimport matplotlibimport matplotlib.pyplot as plt prepares data

Then, we need to import the data including time, displacement, and speed into Python. It should be noted here that according to the conventional idea, we only need to assign these three types of data to different variables, but this drawing cannot do so directly.

Because, as we can see from figure 1, the map is composed of many tracks, that is, each car is a set of data, and depends on time changes, and there is a sequence.

For example, in the same lane, No. 1 enters the study area first, then its data are recorded; then, car No. 2 enters the study area, and the position change, instantaneous speed and time are also recorded. However, the time here is different and goes by gradually.

One idea is to draw all vehicles at the same time: the X axis is a time change and the Y axis is a position change image. However, this operation requires the data of each car to be prepared, which is not realistic for drawing the track map of 300,400 cars at the same time.

In order to solve this problem, a feasible idea is to cycle to draw the trajectory of each car over time. In this way, the data can be read only once, and then drawn circularly in the same coordinate quadrant according to the vehicle ID. Because there is a sequence of each car, there is no need to worry about track overlap between each car.

So, what we need to do in this step is:

Read the underlying data set and filter out the lane data that needs to be used, such as Lane 3

The ID of all vehicles in the lane needs to be extracted and sorted according to chronological order, that is, according to the data label Global_Time. This is the global time.

Therefore, we can write the following code (all code can slide left and right):

# read data data = pd.read_csv (ringing F:\ NGSIMData.csv') # extract lane data lanedata = data [data.Lane _ ID = = 3] # extract vehicle number x_vehID = lanedata.drop_duplicates (['Vehicle_ID']) # sort x_vehID = x_vehID.sort_values (by='Global_Time') according to Global_Time in chronological order # reset the index of sorted vehicle ID Convenient index x_vehID = x_vehID.reset_index (drop = True) basic settings and drawing

So far, we have extracted the data of a certain lane, and all the vehicle numbers have been extracted, in chronological order. At this point, you only need to draw the trajectory of each car in a loop as mentioned earlier. Before we begin, we need to preset the size of the image, as well as the font properties.

# Import package or from matplotlib.font_manager import FontProperties#-like preset font types related to font attributes, size font = FontProperties (fname=r "C:\ Windows\ Fonts\ times.TTF", size=10) # set the size of the canvas plt.figure (figsize= (10,4))

The next step is to cycle through the trajectory map. Here are a few questions that need to be explained:

Since it is a circular drawing, it is natural that the idea of each drawing is exactly the same, which is embodied in the code.

For a single drawing, you only need to correspond to all the data through the first vehicle ID index, and then assign time, displacement and speed to x, y and v, respectively.

Note that for time, NGSIM gives the timestamp format, which needs to be converted

Note that for distance and speed, the units given by NGSIM are feet, which need to be converted

The time will be reflected in the X axis, the distance in the Y axis, and the speed in the color of the track line.

Among them, there is also a thorny problem. That is, suppose a vehicle enters a lane for a period of time, then changes to another lane, and then, after a period of time, the vehicle changes to the current lane. In this way, there is a trajectory in the first half of time, there is no trajectory in the middle, and there is a trajectory in the second half.

In this case, if we choose to draw a line chart, it will connect the broken parts directly with line segments, which is the characteristic of the line chart. However, for such phenomena, we do not expect them to be connected, that is, in a period of time without a track, it is best to be blank.

In order to solve this problem, I chose the scatter plot. Because the frequency of data collected by NGSIM is 0.1s, the data points are very dense, that is to say, for continuous trajectories, even if we use scatter plot, the effect is similar to broken line. For example:

Note that there is a disconnected area in the upper right corner, and if it is drawn with a line chart, it will not have the effect it should have.

Another problem is the handling of color, that is, the need to correspond the speed value of each car to the track point at the same time. At this point, the scatter chart can map the color of the scatter to the numerical value, which is what we need, specifically the cantiv in the code, but this command only maps the speed value to the color.

If you want to apply a color theme to a track map, you need to do two things:

Define the color theme, that is, the command cmap='jet_r' in the scatter chart

Because we need to set up the color bar legend later, we need to normalize the color values in the color bar with the colors in the track map and make them correspond one by one.

We give the code to draw the trajectory-velocity diagram for this loop:

I = 0while I

< (len(x_vehID)-1): # 循环绘制轨迹图 cardata = lanedata[lanedata.Vehicle_ID == x_vehID[i]] # 将时间赋值给变量 x x = cardata['Global_Time'] # 计算相对移动距离,并赋值给变量 y y = np.sqrt(np.square(cardata['Local_Y']) + np.square(cardata['Local_X']) ) # 将速度赋值给变量 v,同时定义速度为颜色映射 v = cardata['v_Vel'] #设定每个图的colormap和colorbar所表示范围是一样的,即归一化 norm = matplotlib.colors.Normalize(vmin=0, vmax=25) # 绘制散点图 ax = plt.scatter(x,y, marker = '.', s=1, c=v, cmap='jet_r', norm = norm) print(i) i = i + 1 其中,我们对 y 值求了平方和的开方,也就是根据车辆的横纵坐标计算位移。我们还将绘制的散点图 ax = plt.scatter 赋给了 ax ,方便后边对散点图的属性进行设置。 这里需要注意的是,对于散点的绘制,我们利用循环解决。而对于坐标轴等的设置,只需设置一次,无需循环。到这里,我们可以得到一个不完美的轨迹-速度图: 三维数据用二维图像呈现,如何利用 Python 绘制酷炫的 车辆轨迹

For some reason, there are a large number of gaps on both sides of the preliminary drawing, which may be due to my problems in the data filtering phase, or that these do not have data points at all. In any case, this does not affect us to learn to draw this kind of image.

4. Beautify the image and add a color bar legend

At this point, you need to add a color bar legend to the above image to represent the speed values corresponding to different colors. Here, you only need two lines of code:

# add color bar plt.clim (0,25) plt.colorbar ()

You can get the image shown below, in which the color theme is modified:

Note here that there is a line of code inside the code of the loop drawing:

# set the range represented by colormap and colorbar of each graph is the same, that is, normalized norm = matplotlib.colors.Normalize (vmin=0, vmax=25)

This line of code determines that the color in the color bar legend is consistent with the color in the track on the left, that is, the track must be drawn and rendered according to the levels set by the color bar.

If there is no line of code, even if you add the code of the color bar, the color bar drawn does not correspond to the trajectory on the left, you can try to see ~

Add horizontal and vertical axes and scale values

This operation is more conventional, according to their own needs to add, regular code casually online search, including the scale is worth setting and so on.

This step only focuses on one point: the X axis is drawn using timestamp data, and because the values are too dense, I turned off the scale value of the X axis in the picture. If you want to display the time format shown in figure 1, one possible way is to add text to the image.

That is, to manually place the time on the scale you want to prevent, let's first look at a set of code:

# set the X axis scale plt.text (x, y, '8plt.text 05mm, fontproperties=font2) plt.text (x, y,' 8plt.text 10mm, fontproperties=font2) plt.text (x, y, '8plt.text 15mm, fontproperties=font2) plt.text (x, y,' 8plt.text 20mm, fontproperties=font2)

With this set of code, we can place the set time at the location specified in the diagram, based on the coordinates (xmemy).

Finally, an image that you think is perfect is attached for your reference:

The coordinate axis is set to Chinese characters because it is more difficult to deal with when Chinese characters and English appear at the same time. You can try to adjust them.

At this point, I believe you have a deeper understanding of "how to use Python to draw cool vehicle tracks". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report