matplotlib-展开以数据单位为指定宽度的行? [英] matplotlib - Expand the line with specified width in data unit?

查看:64
本文介绍了matplotlib-展开以数据单位为指定宽度的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题有点类似于此问题在数据坐标中给出宽度的直线.使我的问题更具挑战性的是,与链接的问题不同,我希望扩展的部分是随机的.

My question is a bit similar to this question that draws line with width given in data coordinates. What makes my question a bit more challenging is that unlike the linked question, the segment that I wish to expand is of a random orientation.

假设线段从(0, 10)变为(10, 10),我希望将其扩展为6的宽度.那就简单了

Let's say if the line segment goes from (0, 10) to (10, 10), and I wish to expand it to a width of 6. Then it is simply

x = [0, 10]
y = [10, 10]
ax.fill_between(x, y - 3, y + 3)

但是,我的线段是随机方向.也就是说,它不一定沿着x轴或y轴. 具有一定的坡度.

However, my line segment is of random orientation. That is, it is not necessarily along x-axis or y-axis. It has a certain slope.

线段s被定义为其起点和终点的列表:[(x1, y1), (x2, y2)].

A line segment s is defined as a list of its starting and ending points: [(x1, y1), (x2, y2)].

现在,我希望将线段扩展到一定宽度w.该解决方案适用于任何方向的线段.该怎么做?

Now I wish to expand the line segment to a certain width w. The solution is expected to work for a line segment in any orientation. How to do this?

更新:plt.plot(x, y, linewidth=6.0)无法解决问题,因为我希望宽度与数据单位相同.

UPDATE: plt.plot(x, y, linewidth=6.0) cannot do the trick, because I want my width to be in the same unit as my data.

推荐答案

仅需添加到上一个答案(尚无法评论),这是一个使该过程自动化的函数,而无需使用相等的轴或的启发式值.标签为0.8.调用此函数后,需要固定轴的数据限制和大小,而不能更改.

Just to add to the previous answer (can't comment yet), here's a function that automates this process without the need for equal axes or the heuristic value of 0.8 for labels. The data limits and size of the axis need to be fixed and not changed after this function is called.

def linewidth_from_data_units(linewidth, axis, reference='y'):
    """
    Convert a linewidth in data units to linewidth in points.

    Parameters
    ----------
    linewidth: float
        Linewidth in data units of the respective reference-axis
    axis: matplotlib axis
        The axis which is used to extract the relevant transformation
        data (data limits and size must not change afterwards)
    reference: string
        The axis that is taken as a reference for the data width.
        Possible values: 'x' and 'y'. Defaults to 'y'.

    Returns
    -------
    linewidth: float
        Linewidth in points
    """
    fig = axis.get_figure()
    if reference == 'x':
        length = fig.bbox_inches.width * axis.get_position().width
        value_range = np.diff(axis.get_xlim())
    elif reference == 'y':
        length = fig.bbox_inches.height * axis.get_position().height
        value_range = np.diff(axis.get_ylim())
    # Convert length to points
    length *= 72
    # Scale linewidth to value range
    return linewidth * (length / value_range)

这篇关于matplotlib-展开以数据单位为指定宽度的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆