python - 将 bbox_inches 设置为 'tight' 进行保存会更改显示坐标
问题描述
我的问题是对这个问题的一种跟进。我使用接受的答案中提出的解决方案将一些图像作为刻度标签:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.image import BboxImage,imread
from matplotlib.transforms import Bbox
# define where to put symbols vertically
TICKYPOS = -.6
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
plt.xlim((0,10))
plt.ylim((0,10))
# Remove tick labels
ax.get_xaxis().set_ticklabels([])
# Go from data coordinates to display coordinates
lowerCorner = ax.transData.transform((.8,TICKYPOS-.2))
upperCorner = ax.transData.transform((1.2,TICKYPOS+.2))
bbox_image = BboxImage(Bbox([lowerCorner,upperCorner]),
norm = None,
origin=None,
clip_on=False)
bbox_image.set_data(imread('thumb.png'))
ax.add_artist(bbox_image)
其中thumb.png是我想作为刻度标签放置的图像示例。
然后我保存图像,plt.savefig("bbox_large.png")
它完美地工作:
不幸的是,图片周围还有很多空白区域。我尝试使用删除它plt.savefig("bbox_tight.png",bbox_inches='tight')
。但是定位搞砸了:
据我对matplotlib的理解,问题在于实际改变显示坐标系的bbox_inches='tight'
选项savefig
,即原点不在同一个地方。该图以某种方式正确显示,但似乎添加到轴的艺术家的坐标不会自动更新。
我尝试使用以下方法考虑额外的艺术家:
plt.savefig("bbox_tight_extra.png",bbox_extra_artists=[bbox_image],bbox_inches='tight')
但它给出了相同的结果。
我还尝试使用事件管理器手动更新显示坐标:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.image import BboxImage,imread
from matplotlib.transforms import Bbox
def ondraw(event):
# Go from data coordinates to display coordinates
lowerCorner = ax.transData.transform((.8,TICKYPOS-.2))
upperCorner = ax.transData.transform((1.2,TICKYPOS+.2))
bbox_image = BboxImage(Bbox([lowerCorner,upperCorner]),
norm = None,
origin=None,
clip_on=False)
bbox_image.set_data(imread('thumb.png'))
ax.add_artist(bbox_image)
# define where to put symbols vertically
TICKYPOS = -.6
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
plt.xlim((0,10))
plt.ylim((0,10))
# Remove tick labels
ax.get_xaxis().set_ticklabels([])
fig.canvas.mpl_connect('draw_event', ondraw)
但它也给出了相同的结果。我假设这是因为我没有明确使用event
变量,因此我没有使用更新的显示坐标系,transData
也就是说我使用的不是正确的。
如何避免图像位置混乱bbox_inches='tight'
?
解决方案
推荐阅读
- github - 如何打开从 GitHub 下载的这个软件?
- ios - 如何获取wilon登录用户单位列表
- c++ - 没有得到预期的输出...代码意外终止(hackerrank 堆栈问题)
- java - 如何使用 Retrofit 在 android 应用程序中获取嵌套的 JSON 响应?
- sql - 需要获取 SQL Sum(Column B) - Sum(Column A)
- c# - 如何从 MVC 应用程序中的请求中读取值?
- git - 如何使用 git 将本地分支与远程分支合并?
- c# - 使用 Selenium 用 C# 开发的 Windows 服务,Chrome 无法在服务器中打开
- c# - 消息在 Confluent Kafka Dotnet 中丢失
- python - 使用两个 for 循环进行列表比较时的性能优化