Last active
November 28, 2018 14:50
-
-
Save Datseris/7df75c85e9b10944e32c53af9b7d06e2 to your computer and use it in GitHub Desktop.
Various pieces of code that help me make nice figures.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# && Exporting to movie: | |
framerate = 5 | |
anim = `ffmpeg -y -framerate $(framerate) -start_number 1 -i $(savename)_%d.png | |
-c:v libx264 -pix_fmt yuv420p -preset veryslow -profile:v baseline -level 3.0 $(savename).mp4` | |
run(anim) | |
# To reduce movie size, you can add the option: | |
`-b:v 2048k` | |
# lower number = lower size = lower quality | |
if deletefigs | |
for i in 1:N | |
rm(savename*"_$(i).png") | |
end | |
end | |
# Add nice textbox, similar to legend: | |
bbox = Dict(:boxstyle => "round,pad=0.3", :facecolor=>"white", :alpha => 0.75) | |
text(0.05, 0.90, "text", bbox=bbox, transform = gca()[:transAxes], size = 22) | |
# && Many PyPlot axis with dedicated colorbars and no ticks: | |
fig = figure(figsize = (10.0, 10.0)) | |
minorticks_off() | |
ax1 = subplot(2,2,1) | |
title("true field \$ $(target) \$") | |
ax2 = subplot(2,2,2, sharey = ax1) | |
title("true field \$ $(source) \$") | |
ax3 = subplot(2,2,3, sharex = ax1) | |
title("cross prediction \$ $(target) \$") | |
ax4 = subplot(2,2,4, sharey = ax1) | |
title("error") | |
# Plot frame n. 1 | |
im1 = ax1[:imshow](Utest[N+1], cmap = "BuPu_r") | |
im2 = ax2[:imshow](Vtest[N+1], cmap = "viridis") | |
im3 = ax3[:imshow](Upred[1], cmap = "viridis") | |
im4 = ax4[:imshow](err[1], cmap = "inferno") | |
for (im, ax) in zip([im1,im2,im3,im4], [ax1,ax2,ax3,ax4]) | |
ax[:get_xaxis]()[:set_ticks]([]) | |
ax[:get_yaxis]()[:set_ticks]([]) | |
colorbar(im, ax = ax, fraction=0.046, pad=0.04) | |
# ax[:minorticks_off]() | |
end | |
# && Adding title to an entire figure that is composed of subplots | |
figtitle = "whole title" | |
suptitle(figtitle, fontsize = 20) | |
subplots_adjust(top=0.9) | |
# && Adding colorbars same size as axes (Python) | |
# There are two ways. A total hack one: | |
for (im, ax) in zip([im1,im2,im3,im4], [ax1,ax2,ax3,ax4]) | |
ax[:get_xaxis]()[:set_ticks]([]) | |
ax[:get_yaxis]()[:set_ticks]([]) | |
colorbar(im, ax = ax, fraction=0.046, pad=0.04) | |
# ax[:minorticks_off]() | |
end | |
# And a valid one, taken from http://joseph-long.com/writing/colorbars/ | |
from mpl_toolkits.axes_grid1 import make_axes_locatable | |
fig, (ax1, ax2) = plt.subplots(ncols=2) | |
img1 = ax1.imshow(data) | |
divider = make_axes_locatable(ax1) | |
cax1 = divider.append_axes("right", size="5%", pad=0.05) | |
fig.colorbar(img1, cax=cax1) | |
img2 = ax2.imshow(-data) | |
divider = make_axes_locatable(ax2) | |
cax2 = divider.append_axes("right", size="5%", pad=0.05) | |
fig.colorbar(img2, cax=cax2) | |
# or as a function: | |
def proper_colorbar(mappable): | |
ax = mappable.axes | |
fig = ax.figure | |
divider = make_axes_locatable(ax) | |
cax = divider.append_axes("right", size="5%", pad=0.05) | |
return fig.colorbar(mappable, cax=cax) | |
# && Create a "Distribution plot" With the central distrb. and the marginals on the side | |
# Create some normally distributed data | |
mean = [0, 0] | |
cov = [[1, 1], [1, 2]] | |
x, y = np.random.multivariate_normal(mean, cov, 3000).T | |
# Set up the axes with gridspec | |
fig = plt.figure(figsize=(6, 6)) | |
grid = plt.GridSpec(4, 4, hspace=0.2, wspace=0.2) | |
main_ax = fig.add_subplot(grid[:-1, 1:]) | |
y_hist = fig.add_subplot(grid[:-1, 0], xticklabels=[], sharey=main_ax) | |
x_hist = fig.add_subplot(grid[-1, 1:], yticklabels=[], sharex=main_ax) | |
# scatter points on the main axes | |
main_ax.plot(x, y, 'ok', markersize=3, alpha=0.2) | |
# histogram on the attached axes | |
x_hist.hist(x, 40, histtype='stepfilled', | |
orientation='vertical', color='gray') | |
x_hist.invert_yaxis() | |
y_hist.hist(y, 40, histtype='stepfilled', | |
orientation='horizontal', color='gray') | |
y_hist.invert_xaxis() | |
#### ---- Plot colorbar and grayscale equivalent | |
from matplotlib.colors import LinearSegmentedColormap | |
def grayscale_cmap(cmap): | |
"""Return a grayscale version of the given colormap""" | |
cmap = plt.cm.get_cmap(cmap) | |
colors = cmap(np.arange(cmap.N)) | |
# convert RGBA to perceived grayscale luminance | |
# cf. http://alienryderflex.com/hsp.html | |
RGB_weight = [0.299, 0.587, 0.114] | |
luminance = np.sqrt(np.dot(colors[:, :3] ** 2, RGB_weight)) | |
colors[:, :3] = luminance[:, np.newaxis] | |
return LinearSegmentedColormap.from_list(cmap.name + "_gray", colors, cmap.N) | |
def view_colormap(cmap): | |
"""Plot a colormap with its grayscale equivalent""" | |
cmap = plt.cm.get_cmap(cmap) | |
colors = cmap(np.arange(cmap.N)) | |
cmap = grayscale_cmap(cmap) | |
grayscale = cmap(np.arange(cmap.N)) | |
fig, ax = plt.subplots(2, figsize=(6, 2), | |
subplot_kw=dict(xticks=[], yticks=[])) | |
ax[0].imshow([colors], extent=[0, 10, 0, 1]) | |
ax[1].imshow([grayscale], extent=[0, 10, 0, 1]) | |
view_colormap("viridis") | |
### ------ Hide tick labels but keep ticks themselves | |
figure() | |
ax1 = subplot(2, 2, 1) | |
ax2 = subplot(2, 2, 2) | |
ax3 = subplot(2, 2, 3) | |
ax4 = subplot(2, 2, 4) | |
# warning: this does not work if you sharex or sharey | |
for ax in (ax1, ax2); ax[:get_xaxis]()[:set_ticklabels]([]); end | |
for ax in (ax2, ax4); ax[:get_yaxis]()[:set_ticklabels]([]); end | |
#### __-_---___ Get specific color from a colormap | |
import matplotlib | |
cmap = matplotlib.cm.get_cmap('Spectral') | |
rgba = cmap(0.5) | |
print(rgba) # (0.99807766255210428, 0.99923106502084169, 0.74602077638401709, 1.0) |
Remove ticks from a sharedx axis without changing all axis:
sca(c2)
setp(c2[:get_xticklabels](), visible=false)
tick_params(axis="x", which="both", length=0)
Excellent subplot letter for all axes immediatelly:
bbox = Dict(:boxstyle => "round,pad=0.3", :facecolor=>"white", :alpha => 1.0)
for (l, ax) in zip('a':'e', gcf().o.get_axes())
sca(ax)
ax.text(0.95, 0.95, string(l), size = SUBPLOT,
transform = ax[:transAxes], bbox = bbox, ha = "center", va = "center", zorder =5)
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Put a label over many x-axis (i.e. put the label on the figure as text)