Issue
I want generate a contour plot/heat map with a color bar and then add an annotation box. This figure is ugly, but gets at what I want:
add_subplot()
is not enough. If I try to put everything in the same subplot, the box gets covered up. I can get around this by making it dragable and then futzing with the size of the image, but this is no good. I am going to have to make several of these images, all of a standard size, and I can't fight with the size over and over again.
I tried axes()
as well, putting the box in a separate axis. But that generates a new window for plotting that covers up most of my color bar. I guess there would be ways to make the window completely transparent. But when I get to that point, I think my approach must be completely wrong.
This doesn't seem like it should be so hard. Any ideas?
Solution
Annotation box to contour map:
Done like this:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
from numpy.random import randn
from mpl_toolkits.axes_grid1.axes_divider import HBoxDivider
import mpl_toolkits.axes_grid1.axes_size as Size
def make_heights_equal(fig, rect, ax1, ax2, ax3, pad):
# pad in inches
h1, v1 = Size.AxesX(ax1), Size.AxesY(ax1)
h2, v2 = Size.AxesX(ax2, 0.1), Size.AxesY(ax2)
h3, v3 = Size.AxesX(ax3), Size.AxesY(ax3)
pad_v = Size.Scaled(1)
pad_h = Size.Fixed(pad)
my_divider = HBoxDivider(fig, rect,
horizontal=[h1, pad_h, h2, pad_h, h3],
vertical=[v1, pad_v, v2, pad_v, v3])
ax1.set_axes_locator(my_divider.new_locator(0))
ax2.set_axes_locator(my_divider.new_locator(2))
ax3.set_axes_locator(my_divider.new_locator(4))
# Make plot with vertical (default) colorbar
fig = plt.figure()
img_ax = fig.add_subplot(131)
bar_ax = fig.add_subplot(132)
ann_ax = fig.add_subplot(133)
data = np.clip(randn(250, 250), -1, 1)
im = img_ax.imshow(data, interpolation='nearest', cmap=cm.coolwarm)
# Add colorbar, make sure to specify tick locations to match desired ticklabels
cbar = fig.colorbar(im, cax=bar_ax, ticks=[-1, 0, 1])
cbar.ax.set_yticklabels(['< -1', '0', '> 1'])# vertically oriented colorbar
ann_ax.axis('off')
ann_ax.annotate("Hello, I'm an annotation", (0.5, 0.5),
xycoords="axes fraction", va="center", ha="center",
bbox=dict(boxstyle="round, pad=1", fc="w"))
make_heights_equal(fig, 111, img_ax, bar_ax, ann_ax, 0.2)
plt.savefig("try.png")
Answered By - brice
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.