Search code examples
pythonrheatmaplevelplot

tweaking colours and scales of heatmap in R


I am making an heatmap using R and the function levelplot() from lattice.

The commands I am using are:

data<-read.table("data_corr", header=T) 
library(gplots)
library(lattice)
z<-cor(data)
levelplot(z)

and I get a figure like this

one

Three things:

(a) Row labels are smudged, how this can be resolved to get more clear row labels?

(b) How can I use the colours red, green and blue instead of default (pink, white and blue)?

(c) Is it possible to tweak the scale from 0.90 to 1 instead of 0.84?

Solutions in python are also welcomed, in that case I have a correlation file of 90*90 (row * column), say filename is z.txt.


Solution

  • In python's matplotlib, the answers to your questions are:

    (a) Plot with the imshow option interpolation="nearest"

    (b) Colormaps can be chosen in the imshow option cmap=cm.jet for example. More examples here.

    (c) To scale, I'm assuming you want to only show values in the threshold and have the colorbar map accordingly. Use imshow option vmax and vmin.

    Here is a minimal working example:

    import numpy as np
    import pylab as plt
    
    # Create random matrix, save it to a text file
    N = 90
    A = np.random.random((N,N))
    np.fill_diagonal(A,.95)
    np.savetxt("z.txt",A)
    
    # Load the data
    A = np.loadtxt("z.txt")
    
    # Apply a mask so values below .9 don't show
    A[A<.9] = None
    
    # Scale the values from .9 to 1.0 using vmin,vmax
    plt.imshow(A, interpolation='nearest', vmin=.9,vmax=1.0,cmap=plt.cm.jet)
    plt.colorbar()
    plt.show()
    

    enter image description here