首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在matplotlib中绘制一条直线,以使绘制的直线的边缘(而不是中心)跟随绘制的数据?

如何在matplotlib中绘制一条直线,以使绘制的直线的边缘(而不是中心)跟随绘制的数据?
EN

Stack Overflow用户
提问于 2013-01-26 03:14:30
回答 1查看 1.7K关注 0票数 1

我正在制作一个数字,用来在高速公路地图上显示交通状况。其想法是,对于每个高速公路段,我将绘制两条线-一条表示方向。每条线的厚度将对应于该方向上的交通量。我需要绘制线条,以便绘制的线条的左侧边缘(相对于行驶方向)遵循公路线段的形状。我想以数据坐标指定形状,但我想以点为单位指定线条的粗细。

我的数据是这样的:

代码语言:javascript
运行
复制
[[((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)分别是正向和反向的交通量

外观很重要:结果应该是漂亮的。

EN

回答 1

Stack Overflow用户

发布于 2013-01-29 00:48:13

我想出了一个使用matplotlib.transforms.Transformshapely.geometry.LineString.parallel_offset的解决方案。

请注意,shapely的parallel_offset方法有时会返回MultiLineString,但此代码不会处理该值。我已经改变了第二个形状,这样它就不会自己交叉,以避免这个问题。我认为这个问题在我的应用程序中很少发生。

另一个注意事项: matplotlib.transforms.Transform的文档似乎暗示由transform方法返回的数组必须与作为参数传递的数组的形状相同,但是在transform方法中添加额外的点来绘制似乎是可行的。

代码语言:javascript
运行
复制
#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()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14529928

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档