想知道matplotlib pyplot为什么不调整边距

2024-09-22 16:27:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在绘图中添加页边距,这样0.0不是在边缘角上,0.0会稍微远离角点。我在看the docs,似乎添加这行plt.margins(x_margin, y_margin)应该会添加填充。但是,不管函数调用如何,下面的输出仍然是相同的,并且仍然缺少边距填充。在

enter image description here

生成的示例代码:

import matplotlib.pyplot as plt
plt.plot([0, 0.1, 0.3, 0.5, 0.7, 0.9, 1], [0.16, 0.17, 0.18, 0.19, 0.2, 0.21, 0.22], 'ro')
plt.axis([0, 1, 0.15, 0.3])
# Create a 10% (0.1) and 10% (0.1) padding in the
# x and y directions respectively.
plt.margins(0.1, 0.1)
plt.show()

Tags: andthe代码marginimport绘图示例docs
2条回答

绘制数据后,请尝试以下操作:

x0, x1, y0, y1 = plt.axis()
margin_x = 0.1 * (x1-x0)
margin_y = 0.1 * (y1-y0)
plt.axis((x0 - margin_x,
          x1 + margin_x,
          y0 - margin_y,
          y1 + margin_y))

这里有两个矛盾的说法:
plt.axis([0, 1, 0.15, 0.3])将x轴限制设置为(0,1)。无法使用plt.margins(0.1, 0.1)撤消此操作。在

根据目标是什么,你可以

  • 将轴保留为自动缩放,并设置plt.margins(0.1, 0.1)以获得10%的边距。在
  • 考虑10%页边距,计算所需的限制;例如

    lim = [0, 1, 0.15, 0.3]
    plt.axis( [lim[i] +2*(i%2-.5)*(lim[i//2+1]-lim[i//2])*0.1 for i in range(4)] )
    

相关问题 更多 >