Search code examples
rkernel-density

filled.contour in R: how to make the same density is same color


I need to plot 2-dimentional density plot using filled.contour in R. I have two datasets and plot them in two fill.contour. I do not have 10 reputations here and I could not post my figures here. I post my codes here and hope it can help to find out the problem.

library(MASS)
density <- kde2d(multi_ligand[,21], multi_ligand[,7])
filled.contour(density,
    color.palette=colorRampPalette(c('white','blue','yellow','red','darkred')),
    xlab=colnames(single_ligand[21]),
    ylab=colnames(single_ligand[7])
)

density1 <- kde2d(single_ligand[,21], single_ligand[,7])
filled.contour(density1,
    color.palette=colorRampPalette(c('white','blue','yellow','red','darkred')),
    xlab=colnames(single_ligand[21]),
    ylab=colnames(single_ligand[7])
)

The problem is I found that in these two plots, the color in the same density is not same. For example, in the first plot, density 0.06 is yellow, however, in the second plot, density 0.06 is blue. I use the same color scale in these two plots. In order to make these two plots comparable, I want to use same color in the same density in these two plots.

Could any please tell me that how should I change my setting to make it right?


Solution

  • By default filled.contour will adjust the blocks of color to evenly cover the range of z, or in this case density, values for each data set. If you want the exact same levels to be used on both plots, you will need to specify them yourself. Here is some code that will specify levels that will cover the range of both data sets.

    #sample data
    set.seed(15)
    ax<-rnorm(50) #like multi_ligand[,21]
    ay<-rnorm(50) #like multi_ligand[,7]
    bx<-rnorm(75,2, .5) #like single_ligand[,21]
    by<-rnorm(75,2, .5) #like single_ligand[,7]
    
    #calculate both densities
    density <- kde2d(ax, ay)
    density1 <- kde2d(bx, by)
    
    #make levels that cover both ranges of z values
    lvls <- pretty(range(density$z, density1$z),20)
    
    #draw both plots using the same levels
    filled.contour(density,
        color.palette=colorRampPalette(c('white','blue','yellow','red','darkred')),
        levels=lvls
    )
    
    filled.contour(density1,
        color.palette=colorRampPalette(c('white','blue','yellow','red','darkred')),
        levels=lvls
    )
    

    Which produce these two plots

    sample output