如何在 Matplotlib 中设置纵横比 | 您所在的位置:网站首页 › 调整图表的大小为锁定纵横比、高10厘米 › 如何在 Matplotlib 中设置纵横比 |
如何在 matplotlib 中设置纵横比经过 本杰明·安德森博
7月 27, 2023
指导
0 条评论 matplotlib 图的纵横比是指轴缩放的纵横比,即 y 单位与 x 单位的比率。 可以使用matplotlib.axes.Axes.set_aspect()函数修改此比率。 在幕后, set_aspect()函数实际上改变了所谓的数据坐标系,但在实践中我们通常想要改变显示坐标系。 为了方便这种转换,我们可以使用这段代码: #define y-unit to x-unit ratio ratio = 1.0 #get x and y limits x_left, x_right = ax. get_xlim () y_low, y_high = ax. get_ylim () #set aspect ratio ax. set_aspect ( abs ((x_right-x_left)/(y_low-y_high))*ratio)让我们看一下在实践中使用此函数的示例。 第 1 步:创建基本 Matplotlib 绘图首先,让我们使用 Matplotlib 创建一个简单的折线图: import matplotlib.pyplot as plt #define matplotlib figure and axis fig, ax = plt. subplots () #create simple line plot ax. plot ([0, 10],[0, 20]) #displayplot plt. show ()请注意,x 轴比 y 轴长。我们尝试将纵横比设置为1,即x轴和y轴应该相等: import matplotlib.pyplot as plt #define matplotlib figure and axis fig, ax = plt. subplots () #create simple line plot ax. plot ([0, 10],[0, 20]) #attempt to set aspect ratio to 1 ax. set_aspect (1) #displayplot plt. show ()请注意,这并没有按预期工作。 y 轴比 x 轴长得多。 步骤 3:设置宽高比(正确的方法)下面的代码展示了如何使用简单的计算来设置正确的宽高比: import matplotlib.pyplot as plt #define matplotlib figure and axis fig, ax = plt. subplots () #create simple line plot ax. plot ([0, 10],[0, 20]) #set aspect ratio to 1 ratio = 1.0 x_left, x_right = ax. get_xlim () y_low, y_high = ax. get_ylim () ax. set_aspect ( abs ((x_right-x_left)/(y_low-y_high))*ratio) #displayplot plt. show ()请注意,该图具有我们预期的纵横比。 x 轴和 y 轴的长度相等。 第四步:根据需要调整纵横比如果我们希望 y 轴比 x 轴长,我们可以简单地指定长宽比为大于 1 的数字: import matplotlib.pyplot as plt #define matplotlib figure and axis fig, ax = plt. subplots () #create simple line plot ax. plot ([0, 10],[0, 20]) #set aspect ratio to 3 ratio = 3 x_left, x_right = ax. get_xlim () y_low, y_high = ax. get_ylim () ax. set_aspect ( abs ((x_right-x_left)/(y_low-y_high))*ratio) #displayplot plt. show ()如果我们希望 y 轴比 x 轴短,我们可以简单地指定纵横比为小于 1 的数字: import matplotlib.pyplot as plt #define matplotlib figure and axis fig, ax = plt. subplots () #create simple line plot ax. plot ([0, 10],[0, 20]) #set aspect ratio to .3 ratio = .3 x_left, x_right = ax. get_xlim () y_low, y_high = ax. get_ylim () ax. set_aspect ( abs ((x_right-x_left)/(y_low-y_high))*ratio) #displayplot plt. show ()您可以在此处找到更多 Matplotlib 教程。 关于作者大家好,我是本杰明,一位退休的统计学教授,后来成为 Statorials 的热心教师。 凭借在统计领域的丰富经验和专业知识,我渴望分享我的知识,通过 Statorials 增强学生的能力。了解更多 添加评论取消回复 |
CopyRight 2018-2019 实验室设备网 版权所有 |