Skip to content

Instantly share code, notes, and snippets.

@berceanu
Last active February 28, 2021 13:47
Show Gist options
  • Save berceanu/0f13651b4d4d240faab336d3d87b2cfb to your computer and use it in GitHub Desktop.
Save berceanu/0f13651b4d4d240faab336d3d87b2cfb to your computer and use it in GitHub Desktop.
Example illustrating `imshow` usage, with `origin`, `extent` and `ogrid`.
import numpy as np
from matplotlib import pyplot, colors, cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
def main():
left = -0.5
bottom = -0.5
right = 6.5
top = 5.5
y, x = np.ogrid[
int(bottom + 0.5) : int(top + 0.5), int(left + 0.5) : int(right + 0.5)
]
data = x + y
fig, ax = pyplot.subplots()
img = ax.imshow(
data,
origin="lower",
extent=(left, right, bottom, top),
norm=colors.Normalize(vmin=data.min(), vmax=data.max()),
cmap=cm.get_cmap("cividis"),
)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="4%", pad=0.02)
cbar = ax.figure.colorbar(
img,
cax=cax,
)
cbar.set_label(r"data ($\mathrm{\#}$)")
ax.set_xlabel(r"$x$ ($\mathrm{\#}$)")
ax.set_ylabel(r"$y$ ($\mathrm{\#}$)")
fig.savefig("imshow.png")
pyplot.close(fig)
if __name__ == "__main__":
main()
# data: (6, 7)
[[ 0 1 2 3 4 5 6]
[ 1 2 3 4 5 6 7]
[ 2 3 4 5 6 7 8]
[ 3 4 5 6 7 8 9]
[ 4 5 6 7 8 9 10]
[ 5 6 7 8 9 10 11]]
# x: (1, 7)
[[0 1 2 3 4 5 6]]
# y: (6, 1)
[[0]
[1]
[2]
[3]
[4]
[5]]
# x_edges
[-0.5 0.5 1.5 2.5 3.5 4.5 5.5 6.5]
# y_edges
[-0.5 0.5 1.5 2.5 3.5 4.5 5.5]
import numpy as np
from matplotlib import pyplot, colors, cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
def corners(centers):
"""
Given a 1d array of center positions, compute the positions of the edges
between them.
"""
lengths = np.diff(centers)
inside_corners = centers[:-1] + lengths / 2
leftmost_corner = centers[0] - lengths[0] / 2
rightmost_corner = centers[-1] + lengths[-1] / 2
c = np.insert(inside_corners, 0, leftmost_corner)
corners = np.append(c, rightmost_corner)
return corners
def main():
left = -0.5
bottom = -0.5
right = 6.5
top = 5.5
y, x = np.ogrid[
int(bottom + 0.5) : int(top + 0.5), int(left + 0.5) : int(right + 0.5)
]
data = x + y
x_edges = corners(np.array([0, 1, 2, 3, 4, 5, 6]))
y_edges = corners(np.array([0, 1, 2, 3, 4, 5]))
fig, ax = pyplot.subplots()
img = ax.pcolormesh(
x_edges,
y_edges,
data,
norm=colors.Normalize(vmin=data.min(), vmax=data.max()),
cmap=cm.get_cmap("cividis"),
edgecolor="black",
)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="4%", pad=0.02)
cbar = ax.figure.colorbar(
img,
cax=cax,
)
cbar.set_label(r"data ($\mathrm{\#}$)")
ax.set_xlabel(r"$x$ ($\mathrm{\#}$)")
ax.set_ylabel(r"$y$ ($\mathrm{\#}$)")
fig.savefig("pcolorfast.png")
pyplot.close(fig)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment