在笛卡尔空间中用matplotlib绘制角度包裹的数据

4 投票
1 回答
1945 浏览
提问于 2025-04-17 06:57

也许我把标题弄得比问题还复杂,但我还是来试试吧…!

我有一些角度数据,这些数据在x-y平面上是连续的,跨越了360度到0度的那条线,也就是说,数据点包括358、359、0、1、2等等。

如果我把这些数据点画出来,并设置:

 plt.xlim(0,360)

那么在图的最左边我会看到三个点,在最右边会有两个点。你可以在这里看到这个(更复杂的,实际的)图表(x轴的范围故意反转):

环绕角度的数据集

我真正想要的是把所有的点都画在图的同一个位置,可能是在图的中心。按照这个方案,360到0度的边界左边的x轴是递减的,右边是递增的。

我不想对数据本身进行任何平移或移动(因为数据集很大等等),所以我想用一些matplotlib的小技巧来实现这个。

我打算用hexbin来绘制这些数据点,如果这有什么不同的话。

谢谢你的关注,也提前感谢你的帮助,

戴夫

1 个回答

5

我觉得直接转换你的数据会快很多。x[x>180] -= 360 这个操作非常快。除非你的数据集有好几个GB,不然转换数据所花的时间只需要几毫秒。

所以,这里有个简单的方法(就是转换你的数据):

import matplotlib.pyplot as plt
import numpy as np

# Generate data to match yours...
y = 60 * np.random.random(300) - 20
x = 60 * (np.random.random(300) - 0.5)
x[x < 0] += 360

# Transform the data back to a -180 to 180 range...
x[x > 180] -= 360

# Plot the data
fig, ax = plt.subplots()
ax.plot(x, y, 'b.')

# Set the ticks so that negative ticks represent >180 numbers
ticks = ax.get_xticks()
ticks[ticks < 0] += 360
ax.set_xticklabels([int(tick) for tick in ticks])

plt.show()

enter image description here

不过,如果你想避免转换数据,你可以这样做……不过,这种方法肯定会比直接转换数据慢。虽然可能慢得不明显,但绝对不会更快。

import matplotlib.pyplot as plt
import numpy as np

# Generate data to match yours...
y = 60 * np.random.random(300) - 20
x = 60 * (np.random.random(300) - 0.5)
x[x < 0] += 360

fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True)
fig.subplots_adjust(wspace=0)

ax1.spines['right'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax1.tick_params(right=False)
ax2.tick_params(left=False)
for label in ax2.get_yticklabels():
    label.set_visible(False)

ax1.plot(x[x > 180], y[x > 180], 'b.')
ax2.plot(x[x <= 180], y[x <= 180], 'b.')

ax2.set_xticks(ax2.get_xticks()[1:])

plt.show()

enter image description here

撰写回答