Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

python - Convert matplotlib data units to normalized units

Does anyone know how to convert matplotlib data units into normalized units?

The reason that I need it is that I need to create a subplot on top of another plot. And the default syntax:

plt.axes([0.1,0.1,0.3,0.3])

requires normalized coordinates, but I want to use the data coordinates:

For example this code:

  plt.plot([0,2],[2,4]);
  plt.axes([0.3,.3,0.4,.4])

produces this:

enter image description here But I'd like to be able to define the location of the subplot using the data coordinates of it , something like [0.7,2.5,1.7,3.5]. I've tried to fiddle with axes.transData, axes.get_transform() and the like but didn't succeed to find the right function to do the job

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's one way to do it:

inner axes printed at 0.5, 2.5, 1.0, 0.3 (in outer axes coords)

inner axes printed at 0.5, 2.5, 1.0, 0.3 (in outer axes coords)

You basically need two transformations -- one from src-coords to display, and one from display to dest-coord. From the docs there seems to be no direct way:
http://matplotlib.org/users/transforms_tutorial.html

bb_data = Bbox.from_bounds(0.5, 2.5, 1.0, 0.3)
disp_coords = ax.transData.transform(bb_data)
fig_coords = fig.transFigure.inverted().transform(disp_coords)

ax and fig both carry transformer with them -- to display-coords!
If you call inverted on them, you get an transformer for the inverse direction.

Here's the full code for the above example:

import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox

plt.plot([0,2], [2,4])
fig = plt.gcf()
ax = plt.gca()

bb_data = Bbox.from_bounds(0.5, 2.5, 1.0, 0.3)
disp_coords = ax.transData.transform(bb_data)
fig_coords = fig.transFigure.inverted().transform(disp_coords)

fig.add_axes(Bbox(fig_coords))

plt.show()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...