我正在制作一个数字,用来在高速公路地图上显示交通状况。其想法是,对于每个高速公路段,我将绘制两条线-一条表示方向。每条线的厚度将对应于该方向上的交通量。我需要绘制线条,以便绘制的线条的左侧边缘(相对于行驶方向)遵循公路线段的形状。我想以数据坐标指定形状,但我想以点为单位指定线条的粗细。
我的数据是这样的:
[[((5,10),(-7,2),(8,9)),(210,320)],
[((8,4),(9,1),(8,1),(11,4)),(2000,1900)],
[((12,14),(17,14)),(550,650)]]
其中,例如,((5,10),(-7,2),(8,9))是给出公路路段形状的x,y值的序列,并且(210,320)分别是正向和反向的交通量
外观很重要:结果应该是漂亮的。
发布于 2013-01-29 00:48:13
我想出了一个使用matplotlib.transforms.Transform和shapely.geometry.LineString.parallel_offset的解决方案。
请注意,shapely的parallel_offset
方法有时会返回MultiLineString
,但此代码不会处理该值。我已经改变了第二个形状,这样它就不会自己交叉,以避免这个问题。我认为这个问题在我的应用程序中很少发生。
另一个注意事项: matplotlib.transforms.Transform的文档似乎暗示由transform
方法返回的数组必须与作为参数传递的数组的形状相同,但是在transform
方法中添加额外的点来绘制似乎是可行的。
#matplotlib version 1.1.0
#shapely version 1.2.14
#Python 2.7.3
import matplotlib.pyplot as plt
import shapely.geometry
import numpy
import matplotlib.transforms
def get_my_transform(offset_points, fig):
offset_inches = offset_points / 72.0
offset_dots = offset_inches * fig.dpi
class my_transform(matplotlib.transforms.Transform):
input_dims = 2
output_dims = 2
is_separable = False
has_inverse = False
def transform(self, values):
l = shapely.geometry.LineString(values)
l = l.parallel_offset(offset_dots,'right')
return numpy.array(l.xy).T
return my_transform()
def plot_to_right(ax, x,y,linewidth, **args):
t = ax.transData + get_my_transform(linewidth/2.0,ax.figure)
ax.plot(x,y, transform = t,
linewidth = linewidth,
solid_capstyle = 'butt',
**args)
data = [[((5,10),(-7,2),(8,9)),(210,320)],
[((8,4),(9,1),(8,1),(1,4)),(2000,1900)],
[((12,14),(17,16)),(550,650)]]
fig = plt.figure()
ax = fig.add_subplot(111)
for shape, volumes in data:
x,y = zip(*shape)
plot_to_right(ax, x,y, volumes[0]/100., c = 'blue')
plot_to_right(ax, x[-1::-1],y[-1::-1], volumes[1]/100., c = 'green')
ax.plot(x,y, c = 'grey', linewidth = 1)
plt.show()
plt.close()
https://stackoverflow.com/questions/14529928
复制相似问题