【发布时间】:2015-12-11 18:53:40
【问题描述】:
使用Line2D 在Matplotlib 中的(x1, y1) 和(x2, y2) 两点之间绘制一条线非常简单:
Line2D(xdata=(x1, x2), ydata=(y1, y2))
但在我的特殊情况下,我必须在所有使用数据坐标的常规图上使用 Points 坐标绘制 Line2D 实例。这可能吗?
【问题讨论】:
标签: python matplotlib transform
使用Line2D 在Matplotlib 中的(x1, y1) 和(x2, y2) 两点之间绘制一条线非常简单:
Line2D(xdata=(x1, x2), ydata=(y1, y2))
但在我的特殊情况下,我必须在所有使用数据坐标的常规图上使用 Points 坐标绘制 Line2D 实例。这可能吗?
【问题讨论】:
标签: python matplotlib transform
正如@tom 提到的,关键是transform kwarg。如果您希望将艺术家的数据解释为“像素”坐标,请指定transform=IdentityTransform()。
变换是 matplotlib 中的一个关键概念。转换获取艺术家数据所在的坐标并将它们转换为显示坐标 - 换句话说,屏幕上的像素。
如果您还没有看过它,请快速阅读matplotlib transforms tutorial。我将假设您对该教程的前几段非常熟悉,所以如果您是
例如,如果我们想在整个图形上画一条线,我们会使用类似的东西:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# The "clip_on" here specifies that we _don't_ want to clip the line
# to the extent of the axes
ax.plot([0, 1], [0, 1], lw=3, color='salmon', clip_on=False,
transform=fig.transFigure)
plt.show()
这条线总是从图形的左下角延伸到右上角,无论我们如何交互式地调整/缩放/平移绘图。
您将使用的最常见的转换是ax.transData、ax.transAxes 和fig.transFigure。但是,要绘制点/像素,您实际上根本不需要变换。在这种情况下,您将创建一个不执行任何操作的新转换实例:IdentityTransform。这指定艺术家的数据是“原始”像素。
任何时候您想以“原始”像素进行绘图,请向艺术家指定transform=IdentityTransform()。
如果您想以点为单位,请记住一英寸有 72 个点,对于 matplotlib,fig.dpi 控制“英寸”中的像素数(它实际上与物理显示无关) .因此,我们可以通过一个简单的公式将点转换为像素。
例如,让我们在距离图形左下边缘 30 点处放置一个标记:
import matplotlib.pyplot as plt
from matplotlib.transforms import IdentityTransform
fig, ax = plt.subplots()
points = 30
pixels = fig.dpi * points / 72.0
ax.plot([pixels], [pixels], marker='o', color='lightblue', ms=20,
transform=IdentityTransform(), clip_on=False)
plt.show()
关于 matplotlib 变换的一个更有用的事情是可以添加它们来创建新的变换。这使得创建班次变得容易。
例如,让我们绘制一条线,然后添加另一条在 x 方向上移动 15 个像素的线:
import matplotlib.pyplot as plt
from matplotlib.transforms import Affine2D
fig, ax = plt.subplots()
ax.plot(range(10), color='lightblue', lw=4)
ax.plot(range(10), color='gray', lw=4,
transform=ax.transData + Affine2D().translate(15, 0))
plt.show()
要记住的关键是添加的顺序很重要。如果我们改为使用Affine2D().translate(15, 0) + ax.transData,我们会将事物移动 15 个 data 单位而不是 15 个像素。添加的转换按顺序“链接”(组合是更准确的术语)。
这也使得定义诸如“距离图形右侧 20 个像素”之类的内容变得容易。例如:
import matplotlib.pyplot as plt
from matplotlib.transforms import Affine2D
fig, ax = plt.subplots()
ax.plot([1, 1], [0, 1], lw=3, clip_on=False, color='salmon',
transform=fig.transFigure + Affine2D().translate(-20, 0))
plt.show()
【讨论】:
您可以使用transform 关键字在数据坐标(默认)和坐标轴坐标之间进行切换。例如:
import matplotlib.pyplot as plt
import matplotlib.lines as lines
plt.plot(range(10),range(10),'ro-')
myline = lines.Line2D((0,0.5,1),(0.5,0.5,0),color='b') # data coords
plt.gca().add_artist(myline)
mynewline = lines.Line2D((0,0.5,1),(0.5,0.5,0),color='g',transform=plt.gca().transAxes) # Axes coordinates
plt.gca().add_artist(mynewline)
plt.show()
【讨论】: