Increase Size of Heatmap in Matplotlib - python

My heatmap does not change size when changing the figsize parameters. I use Latex style for my plots and have set general parameters for the plots:
# Ploting:
import matplotlib
from matplotlib import rc
import matplotlib.pyplot as plt
%matplotlib inline
rc('text', usetex=True)
matplotlib.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}']
plt.style.reload_library()
plt.style.use('science')
matplotlib.rcParams['figure.figsize'] = (7.39, 4.567)
matplotlib.rcParams['lines.linewidth'] = 0.5
matplotlib.rcParams["legend.frameon"] = True # When you need legend background color
matplotlib.rcParams['patch.linewidth'] = 0.2
matplotlib.rcParams['axes.grid'] = True
matplotlib.rcParams['grid.color'] = '#b5b5b5'
matplotlib.rcParams['grid.linestyle'] = '-'
matplotlib.rcParams['grid.linewidth'] = 0.2
Here is the code for the actual heatmap:
fig, ax = plt.subplots(figsize = (16,5))
im = ax.imshow(Granger, cmap=cmap, interpolation='none', norm=norm)
cbar = fig.colorbar(im, extend='max')
cbar.cmap.set_over('green')
fig.axes[1].set_visible(False)
# We want to show all ticks...
ax.set_xticks(np.arange(len(Granger_colnames)))
ax.set_yticks(np.arange(len(Granger_rownames)))
# ... and label them with the respective list entries
ax.set_xticklabels(Granger_colnames)
ax.set_yticklabels(Granger_rownames)
#plt.show()
plt.savefig("/content/drive/MyDrive/Plots/Granger.pdf")
I want to space out the rows and columns so that the text is better visible.

Related

How to keep nested axes position while using subplots_adjust

I use the following code to add a colorbar at the top left corner of each subplot.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
# Create figure
fig = plt.figure(figsize=(5, 2))
# Specify geometry of the grid for subplots
gs0 = gridspec.GridSpec(1, 3, wspace=0.7)
# Data
a = np.arange(3*5).reshape(3,5)
for ax_i in range(3):
# Create axes
ax = plt.subplot(gs0[ax_i])
# Plot data
plot_pcolor = plt.pcolormesh(a)
# ******** Plot a nested colorbar inside the plot ********
# Define position of the desired colorbar in axes coordinate
# [(lower left x, lower left y), (upper right x, upper right y)]
ax_coord = [(0.05, 0.5), (0.2, 0.95)]
# Transform the two points from axes coordinates to display coordinates
tr1 = ax.transAxes.transform(ax_coord)
# Create an inverse transversion from display to figure coordinates
inv = fig.transFigure.inverted()
tr2 = inv.transform(tr1)
# Position in figure coordinates [left, bottom, width, height]
datco = [tr2[0,0], tr2[0,1], tr2[1,0]-tr2[0,0], tr2[1,1]-tr2[0,1]]
# Create colorbar axes
cbar_ax = fig.add_axes(datco)
# Plot colorbar
cbar = plt.colorbar(plot_pcolor, cax=cbar_ax)
# ********************************************************
if False:
plt.subplots_adjust(left=0.15, bottom=0.2, right=0.95, top=0.8)
plt.savefig('test.png', dpi=500)
which gives the following plot:
However, if I use the subplots_adjust() function (by replacing False to True in the code above), the colorbars do not move properly:
Do you know how I can handle it?
Using the inset_axes() function from the mpl_toolkits module solves the problem. It is also possible to simply use ax.inset_axes().
Here is the new code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
# Create figure
fig = plt.figure(figsize=(5, 2))
# Specify geometry of the grid for subplots
gs0 = gridspec.GridSpec(1, 3, wspace=0.7)
# Data
a = np.arange(3*5).reshape(3,5)
for ax_i in range(3):
# Create axes
ax = plt.subplot(gs0[ax_i])
# Plot data
plot_pcolor = plt.pcolormesh(a)
axins = inset_axes(ax, width="5%", height="50%", loc='upper left')
# Plot colorbar
cbar = plt.colorbar(plot_pcolor, cax=axins)
# ********************************************************
if True:
plt.subplots_adjust(left=0.15, bottom=0.2, right=0.95, top=0.8)
plt.savefig('test.png', dpi=500)
Here is the result:

add colorbar on voxel

I need to add colorbar on my voxel, where the facecolors base on a array (in my case, the facecolors base on "data" array). This is my script:
x,y,z = np.mgrid[1:10,3:18,0:5]
data = np.random.normal(0,10,[x.shape[0]-1,x.shape[1]-1,x.shape[2]-1])
visiblebox = np.random.choice([True,False],data.shape)
ax = plt.figure().add_subplot(111,projection ='3d')
colors = plt.cm.plasma(data)
ax.voxels(x,y,z,visiblebox,facecolors=colors,alpha = 0.5,edgecolor='k')
plt.colorbar(colors)
plt.show()
i have try this:
fig = plt.figure()
ax = fig.add_subplot(111,projection ='3d')
p = ax.voxels(x,y,z,visiblebox,facecolors=colors,alpha = 0.5,edgecolor='k')
fig.colorbar(p)
But I get error. I am not sure how to get colorbar to work.
Colorbar for matplotlib plot_surface using facecolorsWhen I looked up SO, I found this answer. I'm not sure about the color bar, but I fixed it while looking at the answer and the color bar showed up.
import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib.colors
x,y,z = np.mgrid[1:10,3:18,0:5]
data = np.random.normal(0,10,[x.shape[0]-1,x.shape[1]-1,x.shape[2]-1])
visiblebox = np.random.choice([True,False],data.shape)
ax = plt.figure().add_subplot(111,projection ='3d')
colors = plt.cm.plasma(data)
norm = matplotlib.colors.Normalize(vmin=0, vmax=16)
vox = ax.voxels(x,y,z,visiblebox,facecolors=colors,alpha = 0.5,edgecolor='k')
m = cm.ScalarMappable(cmap=plt.cm.plasma, norm=norm)
m.set_array([])
plt.colorbar(m)
plt.show()

How do I change the fontsize of the base and exponent on my colorbar?

I'd like to change the size of the base and exponent to match the fontsize of the ticks on my colorbar. How can I do this?
for i in xrange(col):
plt.plot( t, x[i], color = s_m.to_rgba(slopes[i]), linewidth = 3 )
cbar = plt.colorbar(s_m)
cbar.formatter.set_powerlimits((0, 0))
cbar.update_ticks()
cbar.ax.tick_params(labelsize=20)
First off, let's cobble together a stand-alone example to demonstrate your problem. You've changed the size of the colorbar's tick labels, but the offset label didn't update. For example, it would be nice if the text at the top of the colorbar matched the size of the tick labels:
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random((10, 10)) * 1e-6
fig, ax = plt.subplots()
im = ax.imshow(data)
cbar = fig.colorbar(im)
cbar.ax.tick_params(labelsize=20)
ax.set(xticks=[], yticks=[])
plt.show()
What you're wanting to change is referred to as the offset_text. In this case, it's the offset text of the y-axis of the colorbar. You'd want to do something similar to:
cbar.ax.yaxis.get_offset_text.set(size=20)
or
cbar.ax.yaxis.offsetText.set(size=20)
As a complete example:
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random((10, 10)) * 1e-6
fig, ax = plt.subplots()
im = ax.imshow(data)
cbar = fig.colorbar(im)
cbar.ax.tick_params(labelsize=20)
ax.set(xticks=[], yticks=[])
cbar.ax.yaxis.get_offset_text().set(size=20)
plt.show()

Colorbar sticking to axes

I've got a small problem with the positioning of a colorbar using matplotlib. I'm plotting several subplots and one of them is an image. I want this image to have a colorbar but I want it to be "stuck" to the figure, so that there is no space between the two axes (the one from the figure and the one from the colorbar). Even if the figure is resized, the colorbar should always stick to the image axes.
PS - I don't mind if ax3 (the axes of my image) is deformed.
Here's what I've got for the moment:
# Imports
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from scipy import *
# Generating data
data = (rand(2048,2048), rand(2048,2048)+1000)
colorplot = "blue"
metadata = ("Test1", "Test2", "spectral")
# Generating figure and subplots
fig = plt.figure()
fig.subplots_adjust(right = 0.8)
gs1 = gridspec.GridSpec(3, 5)
gs1.update(left=0.05,\
right=0.95,\
top=0.95,\
bottom=0.05,\
wspace=0.2,\
hspace=0.05)
ax1 = fig.add_subplot(gs1[0,0])
ax2 = fig.add_subplot(gs1[0,1])
ax3 = fig.add_subplot(gs1[1:3,0:2])
ax4 = fig.add_subplot(gs1[:,2:])
list_axes = [ax1, ax2, ax3, ax4]
for i in list_axes:
i.autoscale_view(tight=False, scalex=False, scaley=True)
# Misc computation
array = data[1]-data[0]
mean_value = np.mean(array)
std_value = np.std(array)
nb_sigma = 5
ax1.imshow(data[0], interpolation = "nearest", cmap = metadata[2])
ax2.imshow(data[1], interpolation = "nearest", cmap = metadata[2])
im = ax3.imshow(array, vmin = np.min(array[array>mean_value-nb_sigma*std_value]), vmax = np.max(array[array<mean_value+nb_sigma*std_value]), interpolation = "nearest", cmap = metadata[2])
ax3.set_adjustable('box-forced')
# Creating axes for the colorbar
axes_cb = fig.add_axes([ax3.get_position().bounds[0],ax3.get_position().bounds[1], ax3.get_position().bounds[2], 0.05])
fig.colorbar(im, cax = axes_cb, orientation = 'horizontal')
axes_cb.yaxis.tick_left()
n, bins, patches = ax4.hist(array.flatten(), color = colorplot, bins = 50, normed = True)
plt.show()
Thank you!

matplotlib: change title and colorbar text and tick colors

I wanted to know how to change the color of the ticks in the colorbar and how to change the font color of the title and colorbar in a figure. For example, things obviously are visible in temp.png but not in temp2.png:
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import randn
fig = plt.figure()
data = np.clip(randn(250,250),-1,1)
cax = plt.imshow(data, interpolation='nearest')
plt.title('my random fig')
plt.colorbar()
# works fine
plt.savefig('temp.png')
# title and colorbar ticks and text hidden
plt.savefig('temp2.png', facecolor="black", edgecolor="none")
Thanks
Previous answer didnt give what I wanted.
This is how I did it:
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import randn
data = np.clip(randn(250,250),-1,1)
data = np.ma.masked_where(data > 0.5, data)
fig, ax1 = plt.subplots(1,1)
im = ax1.imshow(data, interpolation='nearest')
cb = plt.colorbar(im)
fg_color = 'white'
bg_color = 'black'
# IMSHOW
# set title plus title color
ax1.set_title('ax1 title', color=fg_color)
# set figure facecolor
ax1.patch.set_facecolor(bg_color)
# set tick and ticklabel color
im.axes.tick_params(color=fg_color, labelcolor=fg_color)
# set imshow outline
for spine in im.axes.spines.values():
spine.set_edgecolor(fg_color)
# COLORBAR
# set colorbar label plus label color
cb.set_label('colorbar label', color=fg_color)
# set colorbar tick color
cb.ax.yaxis.set_tick_params(color=fg_color)
# set colorbar edgecolor
cb.outline.set_edgecolor(fg_color)
# set colorbar ticklabels
plt.setp(plt.getp(cb.ax.axes, 'yticklabels'), color=fg_color)
fig.patch.set_facecolor(bg_color)
plt.tight_layout()
plt.show()
#plt.savefig('save/to/pic.png', dpi=200, facecolor=bg_color)
(Update: The information in this answer is outdated, please scroll below for other answers which is up to date and better suited to new version)
This can be done by inspecting and setting properties for object handler in matplotlib.
I edited your code and put some explanation in comment:
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import randn
fig = plt.figure()
data = np.clip(randn(250,250),-1,1)
cax = plt.imshow(data, interpolation='nearest')
title_obj = plt.title('my random fig') #get the title property handler
plt.getp(title_obj) #print out the properties of title
plt.getp(title_obj, 'text') #print out the 'text' property for title
plt.setp(title_obj, color='r') #set the color of title to red
axes_obj = plt.getp(cax,'axes') #get the axes' property handler
ytl_obj = plt.getp(axes_obj, 'yticklabels') #get the properties for
# yticklabels
plt.getp(ytl_obj) #print out a list of properties
# for yticklabels
plt.setp(ytl_obj, color="r") #set the color of yticks to red
plt.setp(plt.getp(axes_obj, 'xticklabels'), color='r') #xticklabels: same
color_bar = plt.colorbar() #this one is a little bit
cbytick_obj = plt.getp(color_bar.ax.axes, 'yticklabels') #tricky
plt.setp(cbytick_obj, color='r')
plt.savefig('temp.png')
plt.savefig('temp2.png', facecolor="black", edgecolor="none")
While the other answers are surely correct, it seems this is easier being solved using either styles or specific rcParams, or using the tick_params function
Styles
Matplotlib provides a dark_background style. You may use it e.g. via plt.style.use("dark_background"):
import matplotlib.pyplot as plt
import numpy as np
plt.style.use("dark_background")
fig = plt.figure()
data = np.clip(np.random.randn(150,150),-1,1)
plt.imshow(data)
plt.title('my random fig')
plt.colorbar()
plt.savefig('temp2.png', facecolor="black", edgecolor="none")
plt.show()
Or, if you need to create the same figure with and without black background styles may be used in a context.
import matplotlib.pyplot as plt
import numpy as np
def create_plot():
fig = plt.figure()
data = np.clip(np.random.randn(150,150),-1,1)
plt.imshow(data)
plt.title('my random fig')
plt.colorbar()
return fig
# create white background plot
create_plot()
plt.savefig('white_bg.png')
with plt.style.context("dark_background"):
create_plot()
plt.savefig('dark_bg.png', facecolor="black", edgecolor="none")
Read more about this in the Customizing matplotlib tutorial.
Specific rcParams
You may individually set the required rcParams that compose a style where needed in your script.
E.g. to make any text blue and yticks red:
params = {"text.color" : "blue",
"xtick.color" : "crimson",
"ytick.color" : "crimson"}
plt.rcParams.update(params)
This will automatically also colorize the tickmarks.
Customizing ticks and labels
You may also customize the objects in the plot individually. For ticks and ticklabels there is a tick_params method. E.g. to only make the ticks of the colorbar red,
cbar = plt.colorbar()
cbar.ax.tick_params(color="red", width=5, length=10)
Based on previous answer I added two lines to set the colorbar's box color and colorbar's ticks color:
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import randn
fig = plt.figure()
data = np.clip(randn(250,250),-1,1)
cax = plt.imshow(data, interpolation='nearest')
title_obj = plt.title('my random fig') #get the title property handler
plt.setp(title_obj, color='w') #set the color of title to white
axes_obj = plt.getp(cax,'axes') #get the axes' property handler
plt.setp(plt.getp(axes_obj, 'yticklabels'), color='w') #set yticklabels color
plt.setp(plt.getp(axes_obj, 'xticklabels'), color='w') #set xticklabels color
color_bar = plt.colorbar()
plt.setp(plt.getp(color_bar.ax.axes, 'yticklabels'), color='w') # set colorbar
# yticklabels color
##### two new lines ####
color_bar.outline.set_color('w') #set colorbar box color
color_bar.ax.yaxis.set_tick_params(color='w') #set colorbar ticks color
##### two new lines ####
plt.setp(cbytick_obj, color='r')
plt.savefig('temp.png')
plt.savefig('temp3.png', facecolor="black", edgecolor="none")
Also, you can change the tick labels with:
cax = plt.imshow(data)
cbar = plt.colorbar(orientation='horizontal', alpha=0.8, label ='my label',
fraction=0.075, pad=0.07, extend='max')
#get the ticks and transform it to list, if you want to add strings.
cbt = cbar.get_ticks().tolist()
#edit the new list of ticks, for instance the firs element
cbt[0]='$no$ $data$'
# then, apply the changes on the actual colorbar
cbar.ax.set_xticklabels(cbt)

Categories