Matplotlib轴具有函数axhline
和axvline
,用于在给定的y或x坐标(分别)绘制水平线或垂直线,而与轴上的数据比例无关。
有没有类似的函数来绘制一条常量对角线?例如,如果我有一个具有相似属性域的变量散点图,那么知道它们是否落在y = x
线之上或之下通常是有用的
mean, cov = [0, 0], [(1, .6), (.6, 1)]
x, y = np.random.multivariate_normal(mean, cov, 100).T
y += x + 1
f, ax = plt.subplots(figsize=(6, 6))
ax.scatter(x, y, c=".3")
ax.plot([-3, 3], [-3, 3], ls="--", c=".3")
ax.set(xlim=(-3, 3), ylim=(-3, 3))
这当然可以通过获取轴限制(ax.get_xlim()
等)以编程方式完成,但是a)需要几个额外的步骤,b)在更多数据可能最终出现在绘图上并改变限制的情况下是脆弱的。(实际上,在某些情况下,只需添加常量线本身就会拉伸轴)。
例如,最好只使用ax.axdline(ls="--", c=".3")
,但不清楚matplotlib代码库中是否存在这样的代码。我认为,您所需要做的就是修改axhline
代码,使其在x
和y
的轴坐标中从[0, 1]
绘制。
发布于 2015-01-29 22:10:19
绘制从图的左下角到右上角的对角线将通过以下方式完成
ax.plot([0, 1], [0, 1], transform=ax.transAxes)
使用transform=ax.transAxes
,提供的x
和y
坐标将被解释为轴坐标,而不是数据坐标。
正如@fqq指出的那样,只有当你的x
和y
限制相等时,这才是唯一的身份线。要绘制y=x
线,使其始终延伸到您的图的极限,可以使用类似于@Ffisegydd给出的方法,并可以编写为以下函数。
def add_identity(axes, *line_args, **line_kwargs):
identity, = axes.plot([], [], *line_args, **line_kwargs)
def callback(axes):
low_x, high_x = axes.get_xlim()
low_y, high_y = axes.get_ylim()
low = max(low_x, low_y)
high = min(high_x, high_y)
identity.set_data([low, high], [low, high])
callback(axes)
axes.callbacks.connect('xlim_changed', callback)
axes.callbacks.connect('ylim_changed', callback)
return axes
示例用法:
import numpy as np
import matplotlib.pyplot as plt
mean, cov = [0, 0], [(1, .6), (.6, 1)]
x, y = np.random.multivariate_normal(mean, cov, 100).T
y += x + 1
f, ax = plt.subplots(figsize=(6, 6))
ax.scatter(x, y, c=".3")
add_identity(ax, color='r', ls='--')
plt.show()
发布于 2014-03-01 04:17:41
从屏幕的左下角到右上角绘制一条对角线非常简单,您可以简单地使用ax.plot(ax.get_xlim(), ax.get_ylim(), ls="--", c=".3")
。方法ax.get_xlim()
将简单地返回x轴的当前值(y轴也是如此)。
但是,如果您希望能够使用图形进行缩放,则会变得稍微复杂一些,因为您绘制的对角线将不会更改以匹配新的xlims和ylims。
在这种情况下,您可以使用回调来检查xlims (或ylims)何时发生更改,并相应地更改对角线中的数据(如下所示)。我在this example中找到了回调的方法。欲了解更多信息,请登录网站:here。
import numpy as np
import matplotlib.pyplot as plt
mean, cov = [0, 0], [(1, .6), (.6, 1)]
x, y = np.random.multivariate_normal(mean, cov, 100).T
y += x + 1
f, ax = plt.subplots(figsize=(6, 6))
ax.scatter(x, y, c=".3")
ax.set(xlim=(-3, 3), ylim=(-3, 3))
# Plot your initial diagonal line based on the starting
# xlims and ylims.
diag_line, = ax.plot(ax.get_xlim(), ax.get_ylim(), ls="--", c=".3")
def on_change(axes):
# When this function is called it checks the current
# values of xlim and ylim and modifies diag_line
# accordingly.
x_lims = ax.get_xlim()
y_lims = ax.get_ylim()
diag_line.set_data(x_lims, y_lims)
# Connect two callbacks to your axis instance.
# These will call the function "on_change" whenever
# xlim or ylim is changed.
ax.callbacks.connect('xlim_changed', on_change)
ax.callbacks.connect('ylim_changed', on_change)
plt.show()
请注意,如果您不希望对角线随缩放而改变,则只需删除diag_line, = ax.plot(...
下面的所有内容
发布于 2019-02-04 19:54:03
如果轴在[0,1]
范围内,则可以按以下方式进行解析:
ident = [0.0, 1.0]
plt.plot(ident,ident)
https://stackoverflow.com/questions/22104256
复制相似问题