【问题标题】:Adding diagional line y=x with an offset添加对角线 y=x 和偏移量
【发布时间】:2018-09-20 07:11:24
【问题描述】:

我正在尝试添加 y=x 行以及 y=x 行的偏移量,这比我共享的代码更好。例如,对于 Y=X,我想要 Y=X 的另外两条对角线 +0.5 和 -0.5,但我展示的代码有点难以理解。对此的任何帮助将不胜感激。

    x=np.linspace(0,5,101) 
    y=np.random.normal(x)    # add some noise

    plt.plot(x,y,'r.') # x vs y
    plt.plot(x,x,'k-') # identity line

    plt.plot(x+0.25,x-0.25,'b-') # identity line
    plt.plot(x-0.25,x+0.25,'b-') # identity line

    plt.xlim(0,5)
    plt.ylim(0,5)
    plt.show()

【问题讨论】:

  • 创建一个计算y=mx+b的函数。偏移量相当于更改b
  • 是的,这可以做到,但有没有类似的东西:stackoverflow.com/questions/25497402/…
  • 你到底想要什么?
  • 是否可以像链接中显示的示例一样简单地使用 ax.get_xlim() 和 ax.get_ylim() 但添加我想要的偏移量。
  • 不清楚为什么需要限制。查看更新后的帖子。

标签: python-2.7 matplotlib plot


【解决方案1】:

您似乎希望实现一个为给定偏移量绘制线性线的函数。

import numpy as np
import matplotlib.pyplot as plt


np.random.seed(123)
%matplotlib inline

# Functions
def linear(x, m=1, b=0):
    """Return y values for a line."""
    return x*m + b


def plot_offsets(x, func=linear, thres=0.25, ax=None):
    """Plot lines seperated by the given offset."""
    if ax is None:
        ax = plt.gca()
    half = thres/2.
    ax.plot(x+half, func(x, b=-half), "b-")        # lower
    ax.plot(x-half, func(x, b=half), "b-")         # upper
    return ax


# Data
x_lin = np.linspace(0, 5, 101) 
y_data = np.random.normal(x_lin)                   # add some noise


# Plot
fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(x_lin, y_data, "r.")                       # x vs y
ax.plot(x_lin, linear(x_lin), "k-")                # identity line
plot_offsets(x_lin, thres=0.5, ax=ax)
ax.set_xlim(0, 5)
ax.set_ylim(0, 5)
plt.show()

您的代码中添加了两个函数来抽象绘制线性线和线性“偏移”(给定阈值)。其余大部分添加(np.random.seed_, ax = plt.subplots)都包含在可重现代码中。

输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多