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

时间:2011-11-23 20:46:29

标签: python plot matplotlib axes

也许我的标题比问题更复杂,但是这里......!

我有一些角度数据,在x-y平面上是连续的,跨越360 => 0度线 - 即358,359,0,1,2 ....

如果我正在绘制这些并设置:

 plt.xlim(0,360)

我当然会在情节的最左边有三个点,最右边有两个点。您可以在(更复杂,实际)的图中看到这一点(x轴限制有意颠倒):

the angularly-wrapped dataset

我真正喜欢的是将所有点绘制在绘图窗口中的相同位置周围,也许是朝向绘图的中心。在此方案下,x轴向360°边界的左侧减小,并向右增加。

我不想对数据本身进行任何翻译/转换(它是一个大型数据集等),所以我希望用一些matplotlib-trickery来做这个。

我计划用hexbin绘制数据点,如果这有任何区别的话。

感谢您的关注,并提前感谢您的帮助,

戴夫

1 个答案:

答案 0 :(得分:4)

老实说,我认为只是转换数据会更快。 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

但是,如果你想避免转换你的数据,你可以做这样的事情......但是,100%保证比转换数据要慢。 (可能忽略不计,但速度不会更快。)

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