自学Matplotlib的一些翻译记录

Matplotlib基础教程:数据可视化与图形样式
这篇博客详细介绍了Matplotlib库的基础使用,包括创建Figure、Axes以及Artist的概念。展示了如何绘制简单图表、设置坐标轴、添加标签、使用数学表达式以及注解。同时,讲解了线宽、线型、颜色的设定,以及图例和坐标轴尺度的调整。通过实例代码,演示了如何定制化图形样式和绘制多种数据类型。

Matplotlib

Getting Started

基础使用

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

一个简单的例子

Matplotlib 将你的数据显示在Figure上,每个图片可以包含一个或以上的坐标域(Axes:一个可以用x-y坐标、极坐标、三维坐标表示特定点的区域),通过pyplot.subplots可以创建一个带有坐标的Figure,可以使用Axes.plot在坐标域中画一些数据,例如

fig, ax = plt.subplots()  # Create a figure containing a single axes.
ax.plot([1, 2, 3, 4], [1, 4, 2, 3]);  # Plot some data on the axes.

Figure的组成

Figure可以包含图中的部分
Parts of Figure

最简单的创建一个新的Figure的方式是使用pyplot,下面是创建几种不同样式的Figure的例子

fig = plt.figure()  # an empty figure with no Axes
fig, ax = plt.subplots()  # a figure with a single Axes
fig, axs = plt.subplots(2, 2)  # a figure with a 2x2 grid of Axes
Artist

任何在Figure中可见的元素都被称为Artist,大多数Artist都被绑定至一个Axes

Axes

Axes是Figure中作为绘图的区域,通常包含2个或3个坐标轴(Axis)以及相应的坐标间隔尺度等

绘图函数的输入变量类型

绘图函数期望输入的类型是numpy.arraynumpy.ma.masked_array,
或者是可以被转换为numpy.asarray的数据。一些类数组(array-like)的数据类,例如pandas以及numpy.matrix可能不会像你想要的方式运行,通常先将它们转换为numopy.asarray类型再进行绘图,例如

b = np.matrix([[1, 2], [3, 4]])
b_asarray = np.asarray(b)

大多数方法(methods)也会解析一些寻址类型的数据类型,例如dict,numpy.rearray,pandas.dataFrames。Matplotlib allows you provide the data keyword argument and generate plots passing the strings corresponding to the x and y variables.

np.random.seed(19680801)  # seed the random number generator.
data = {'a': np.arange(50),
        'c': np.random.randint(0, 50, 50),
        'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100

fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
ax.scatter('a', 'b', c='c', s='d', data=data)
ax.set_xlabel('entry a')
ax.set_ylabel('entry b');

编码风格

将常用绘图方式打包成一个函数
def my_plotter(ax, data1, data2, param_dict):
    """
    A helper function to make a graph.
    """
    out = ax.plot(data1, data2, **param_dict)
    return out

data1, data2, data3, data4 = np.random.randn(4, 100)  # make 4 random data sets
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(5, 2.7))
my_plotter(ax1, data1, data2, {'marker': 'x'})
my_plotter(ax2, data3, data4, {'marker': 'o'})

Artists Styles

大多数绘制方法具有Styles可选项,可以通过plot人为设置颜色、线宽、线型等

fig, ax = plt.subplots(figsize=(5, 2.7))
x = np.arange(len(data1))
ax.plot(x, np.cumsum(data1), color='blue', linewidth=3, linestyle='--')
l, = ax.plot(x, np.cumsum(data2), color='orange', linewidth=2)
l.set_linestyle(':')

颜色
fig, ax = plt.subplots(figsize=(5, 2.7))
ax.scatter(data1, data2, s=50, facecolor='C0', edgecolor='k')

线宽、线型、标识符
fig, ax = plt.subplots(figsize=(5, 2.7))
ax.plot(data1, 'o', label='data1')
ax.plot(data2, 'd', label='data2')
ax.plot(data3, 'v', label='data3')
ax.plot(data4, 's', label='data4')
ax.legend()

添加标签

坐标域标签和文字

set_xlabel, set_ylabel, set_title, text

mu, sigma = 115, 15
x = mu + sigma * np.random.randn(10000)
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
# the histogram of the data
n, bins, patches = ax.hist(x, 50, density=1, facecolor='C0', alpha=0.75)

ax.set_xlabel('Length [cm]')
ax.set_ylabel('Probability')
ax.set_title('Aardvark lengths\n (not really)')
ax.text(75, .025, r'$\mu=115,\ \sigma=15$')
ax.axis([55, 175, 0, 0.03])
ax.grid(True)

数学表达式

Matplotlib接受Tex的方程表达式,例如 σ i = 15 \sigma_i = 15 σi=15

ax.set_title(r'$\sigma_i=15$')
附注(Annotations)
fig, ax = plt.subplots(figsize=(5, 2.7))

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2 * np.pi * t)
line, = ax.plot(t, s, lw=2)

ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
            arrowprops=dict(facecolor='black', shrink=0.05))

ax.set_ylim(-2, 2)

图例(legends)
fig, ax = plt.subplots(figsize=(5, 2.7))
ax.plot(np.arange(len(data1)), data1, label='data1')
ax.plot(np.arange(len(data2)), data2, label='data2')
ax.plot(np.arange(len(data3)), data3, 'd', label='data3')
ax.legend()

坐标轴尺度和刻度

尺度

loglog, semilogx, semilogy

fig, axs = plt.subplots(1, 2, figsize=(5, 2.7), layout='constrained')
xdata = np.arange(len(data1))  # make an ordinal for this
data = 10**data1
axs[0].plot(xdata, data)

axs[1].set_yscale('log')
axs[1].plot(xdata, data)

刻度位置和格式

set_xticks

fig, axs = plt.subplots(2, 1, layout='constrained')
axs[0].plot(xdata, data1)
axs[0].set_title('Automatic ticks')

axs[1].plot(xdata, data1)
axs[1].set_xticks(np.arange(0, 100, 30), ['zero', '30', 'sixty', '90'])
axs[1].set_yticks([-1.5, 0, 1.5])  # note that we don't need to specify labels
axs[1].set_title('Manual ticks')

绘制日期和字符串

未完待续

### Hybrid A* Algorithm Implementation for Navigation The Hybrid A* algorithm is an extension of the traditional A* search algorithm designed specifically to handle continuous state spaces and non-holonomic constraints, which are common in robotic vehicles like cars. This method combines discrete grid-based path planning with local trajectory optimization. In robotics or game development contexts where entities have orientation-dependent movement (such as wheeled robots), this approach provides a robust solution that can efficiently find feasible paths while considering vehicle dynamics[^1]. #### Key Components of Hybrid A* - **State Representation**: Each node represents not only position but also heading direction. - **Heuristic Function**: Incorporates both distance-to-goal and steering angle difference between current heading and ideal goal-directed course. - **Trajectory Simulation**: For each potential action at every explored point, simulate short-term motion outcomes based on kinematic models specific to the agent's physics properties. Below demonstrates how one might implement such functionality within Python: ```python import heapq from math import sin, cos, atan2, sqrt, pi class Node: def __init__(self, x=0., y=0., theta=0., g_cost=float('inf'), h_cost=0., parent=None): self.x = x # Position X coordinate self.y = y # Position Y coordinate self.theta = theta # Orientation angle self.g_cost = g_cost # Cost from start to here self.h_cost = h_cost # Estimated cost from here to target self.parent = parent # Parent node reference def hybrid_a_star(start_node, end_node, map_data, resolution=0.1, lookahead_distance=5.0): open_list = [] closed_set = set() heuristic_weight = 1.0 start_node.g_cost = 0 start_node.h_cost = calculate_heuristic(start_node, end_node) heapq.heappush(open_list, (start_node.f_cost(), start_node)) while open_list: _, current_node = heapq.heappop(open_list) if check_goal_reached(current_node, end_node, tolerance=resolution * 2): return reconstruct_path(current_node) closed_set.add((current_node.x, current_node.y)) successors = generate_successors(current_node, map_data, resolution, lookahead_distance) for successor in successors: tentative_g_score = current_node.g_cost + compute_motion_cost(current_node, successor) if ((successor.x, successor.y) not in closed_set or tentative_g_score < successor.g_cost): successor.g_cost = tentative_g_score successor.h_cost = heuristic_weight * calculate_heuristic(successor, end_node) if any([item[1].equals(successor) for item in open_list]): continue heapq.heappush(open_list, (successor.f_cost(), successor)) raise ValueError("No valid path found!") ``` This code snippet outlines core logic behind implementing Hybrid A*, including defining nodes representing states along possible routes; calculating costs associated with traversing these points; expanding reachable locations through simulation steps constrained by physical limitations imposed upon moving objects; prioritizing exploration using weighted estimates towards objectives combined with actual travel expenses incurred thus far during searches conducted over discretized environments represented via occupancy grids or similar structures. --related questions-- 1. What modifications would be necessary when applying Hybrid A* to different types of vehicles? 2. How does incorporating dynamic obstacles affect the performance of Hybrid A* algorithms? 3. Can you explain more about tuning parameters used in heuristics functions within Hybrid A* implementations? 4. In what scenarios could alternative sampling-based planners outperform Hybrid A* methods?
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值