With the below code I can generate a nice correlation plot.
library(corrplot)
df <- data.frame(A=1:10,B=rnorm(10)*(1:10),C=1:10,D=runif(10)*1:10)
df
corrplot(cor(df))
Adding the parameter of bg="black" will change the colour inside the graph to black.
df <- data.frame(A=1:10,B=rnorm(10)*(1:10),C=1:10,D=runif(10)*1:10)
df
corrplot(cor(df),bg="black")
Now If I would like to set the whole graph window to black this should work:
par(bg="black")
df <- data.frame(A=1:10,B=rnorm(10)*(1:10),C=1:10,D=runif(10)*1:10)
df
corrplot(cor(df),bg="black")
But it does not. How to get the whole plotting window to black?
Here is a 2-step way:
# First, we need to plot once, to get the extremes of
# the user coordinates of the plotting region, as set
# by the corrplot function
corrplot(cor(df))
# The extremes are stored
usr <- par("usr")
# New empty plotting window
plot.new()
# Set the new extremes
par(usr=usr)
# Plot a rectangle filled in black, covering the whole plotting window
rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "black")
# Finally, plot the corrplot
corrplot(cor(df), bg="black", add = TRUE)
Related
I am plotting the density of a two-dimensional, weighted spatial point pattern. I'd like to make the plot without a colour scale legend, and save it with no (or minimal) boarders on all sides, like this: My problem is that I can't remove the colour scale legend. Reproducible code below:
## Install libraries:
library(spatstat) #spatial package
library(RColorBrewer) #create custom colour ramps
## Create reproducible data:
data <- data.frame(matrix(ncol = 3, nrow = 50))
x <- c("x", "y", "weight")
colnames(data) <- x
data$x <- runif(50, 0, 20)
data$y <- runif(50, 0, 20)
data$weight <- sample(1:200, 50)
## Set plotting window and colours:
plot.win <- owin(c(0,20), c(0,20)) # plot window as 20x20m
spat.bat.frame <- NULL # create a frame to store values in
cols1<-colorRampPalette(brewer.pal(9,"Blues"))(100) #define colour ramp for density plots
## Create and save plots:
jpeg(filename = "Bad plot.jpeg", res = 300, units = "cm", width = 20, height = 20)
par(mar=c(0,0,0,0),oma=c(0,0,0,0),lwd=1)
ppp_01 <- ppp(x = data$x, y = data$y, window = plot.win)
ppp_02 <- ppp(x = data$x, y = data$y, window = plot.win)
plot(density(ppp_01, weights = data$weights), main=NULL, col=cols1, sigma = 1)
plot(ppp_02, add=TRUE) #add spp points to density plot
dev.off()
I've tried legend=FALSE, auto.key=FALSE, colorkey=FALSE, which don't seem to be compatible with plot() (i.e. they don't give an error but don't change anything). I've also tried some work-arounds like saving a cropped image with dev.off.crop() or by adjusting margins with par(), but haven't been able to completely remove the legend. Does anyone have any suggestions on how to remove a colour scale legend of a density spp (real-valued pixel image) using plot()?
I specifically need to plot the density of the spatial point pattern, to specify a custom colour ramp, and to overlay the spp points onto the density image. I could try plotting with spplot() instead, but I'm not sure this will allow for these three things, and I feel like I'm missing a simple fix with plot(). I can't crop the figures manually after saving from R because there are 800 of them, and I need them all to be exactly the same size and in the exact same position.
Thank you!
Since plot is a generic function, the options available for controlling the plot will depend on the class of object that is being plotted. You want to plot the result of density(ppp_01, weights = data$weights). Let's call this Z:
Z <- density(ppp_01, weights = data$weights, sigma=1)
Note: the smoothing bandwidth sigma should be given inside the call to density
To find out about Z, you can just print it, or type class(Z).
The result is that Z is an object of class"im" (pixel image).
So you need to look up the help file for plot.im, the plot method for class "im". Typing ?plot.im shows that there is an argument ribbon that controls whether or not the colour ribbon is displayed. Simply set ribbon=FALSE in the call to plot:
plot(Z, ribbon=FALSE, main="", col=cols1)
Or in your original code
plot(density(ppp_01, weights=data$weights, sigma=1), main="", col=cols1)
However I strongly recommend separating this into two lines, one which creates the image object, and one which plots the image. This makes it much easier to spot mistakes like the misplacement of the sigma argument.
My problem is related to car package.
I create Kernal plot. However, since legend is too big, I would like to move legend outside the plot are, upper or lower?
Otherwise, I tried with cowplot::get_legend( ), but it did not work properly.
library(car)
mtcars$g <- as.factor(mtcars$vs)
densityPlot(mpg,mtcars$g,show.bw=T, kernel=depan,legend=list(location="topleft",title=NULL))
Probably the easiest thing is to not plot the legend using the densityPlot() function but rather add it separately using legend(). The following code is an example of how this can be done. The resulting figure look like this:
library(car)
mtcars$g <- as.factor(mtcars$vs)
par(mar=c(4,4,4,2))
# obtaining results from kernel density and saving results
# need saved values for bandwidth in legend
# also plots the kernel densities
d <- densityPlot(mtcars$mpg,mtcars$g
,show.bw=T
,kernel=depan
,legend=F # no default legend
,col = c('black','blue')
,lty=c(1,2))
# allows legend outside of plot area to be displayed
par(xpd=T)
# defining location based on the plot coordinates from par('usr')
legend(x=mean(par('usr')[c(1,2)]) # average of range of x-axis
,y=par('usr')[4]+0.015 # top of the y axis with additional shift
,legend = c(paste('0 (bw = ',round(d$`0`['bw'][[1]],4),')',sep='') # extract bw values from saved output and
,paste('1 (bw = ',round(d$`1`['bw'][[1]],4),')',sep='')) # formatting similar to default, except with rounding bw value
,ncol=1 # change to 2 if you want entries beside each other
,lty=c(1,2) # line types, same as above
,col=c('black','blue') # colors, same as above
,lwd=1
,xjust = 0.5 # centers legend at x coordinate
,yjust = 0.5 # centers legend at y coordinate
)
par(xpd=F)
I have a problem, might be a bug in heatmaply or plotly. Colors in the sidebar of a heatmap are not showing the colors I specified. See the code example below, At the end of the code in part # 6) the first plot, plotted using the plot function (simple plot showing the colors), shows the colors correctly (yellow and blue):
The second plot using these colors in a heatmaply side bar (heatmamply side bar with wrong color):
fails to show them correctly and instead what appears to show random colors. In a similar plot with real data there are even red and orange colors in the sidebar (heatmaply sidebar shows red and orange while color range is blue-yellow):
while all codes are generated using a blue yellow color range. Any ideas what might cause this bug and how to show colors in the sidebar consistent with their color code a?
Compare cophenetic similarity between leaves in two trees build on full data and subsample of the data
# 1 ) Generate random data to build trees
set.seed(2015-04-26)
dat <- matrix(rnorm(100), 10, 50) # Dataframe with 50 columns
datSubSample <- dat[, sample(ncol(dat), 30)] #Dataframe with 30 columns sampled from the dataframe with 50
dat_dist1 <- dist(datSubSample)
dat_dist2 <- dist(dat)
hc1 <- hclust(dat_dist1)
hc2 <- hclust(dat_dist2)
# 2) Build two dendrograms, one based on all data, second based a sample of the data (30 out of 50 columns)
dendrogram1 <- as.dendrogram(hc1)
dendrogram2 <- as.dendrogram(hc2)
# 3) For each leave in a tree get cophenetic distance matrix,
# each column represent distance of that leave to all others in the same tree
cophDistanceMatrix1 <- as.data.frame(as.matrix(cophenetic(dendrogram1)))
cophDistanceMatrix2 <- as.data.frame(as.matrix(cophenetic(dendrogram2)))
# 4) Calculate correlation between cophenetic distance of a leave to all other leaves, between two trees
corPerLeave <- NULL # Vector to store correlations for each leave in two trees
for (leave in colnames(cophDistanceMatrix1)){
cor <- cor(cophDistanceMatrix2[leave], cophDistanceMatrix1[leave])
corPerLeave <- c(corPerLeave, unname(cor))
}
# 5) Convert cophenetic correlation to color to show in side bar of a heatmap
corPerLeave <- corPerLeave / max(corPerLeave) #Scale 0 to 1 correlation
byPal <- colorRampPalette(c('yellow', 'blue')) #blue yellow color palette, low correlation = yellow
colCopheneticCor <- byPal(20)[as.numeric(cut(corPerLeave, breaks =20))]
# 6) Plot heatmap with dendrogram with side bar that shows cophenetic correlation for each leave
row_dend <- dendrogram2
x <- as.matrix(dat_dist2)
#### Plot belows use the same color code, normal plot works, however heatmaply shows wrong colors
plot(x = 1:length(colCopheneticCor), y = 1:length(colCopheneticCor), col = colCopheneticCor)
heatmaply(x, colD = row_dend, row_side_colors = colCopheneticCor)
Found the solution, you can use a function for the color with the heatmaply build in row_side_palette parameter. Minimal example code, that can be combined with the code in the question itself to show heatmap with cophenetic distance per leave/species in the sidebar represented by a different color:
ByPal <- colorRampPalette(c('red','blue')) # Bi color palette function to be used in sidebar
heatmaply(m,colD = row_dend, file=fileName1, plot_method= "plotly",colorscale='Viridis',row_side_palette= byPal ,
row_side_colors=data.frame("Correlation cophenetic distances" = corPerLeave, check.names=FALSE))
One problem I did not solve yet is how to show a continuous colorbar in the legend, any suggestions?
I am trying to construct a heatmap in R using a correlation matrix and a p value matrix.
I use this tutorial to build the heatmap without problems. It works perfectly. I can even introduce some values from a second matrix (the p value matrix) in the right cells.
But when I try to highlight the corresponding cells it doesn't work. I use this code to generate the borders.
I use RStudio v0.97 with the packages gplots, RColorBrewer.
The code is :
library(gplots)
library(RColorBrewer)
my_palette <- colorRampPalette(c("red", "yellow", "green"))(n = 299)
nx = 5
ny = 10
mat1 <- matrix(rnorm(nx*ny,100,50),nx,ny)
mat2 <- mat1>150 #matrix used for the example instead of the p value matrix
makeRects <- function(tfMat,border){
cAbove = expand.grid(1:nx,1:ny)[tfMat,]
xl=cAbove[,1]-0.49
yb=cAbove[,2]-0.49
xr=cAbove[,1]+0.49
yt=cAbove[,2]+0.49
rect(xl,yb,xr,yt,border=border,lwd=3)
} #this is the function to make the rectangles/borders
heatmap.2(mat1,
Rowv = FALSE, # don't reorganize columns
cellnote = mat2, # check correspondance between rectangles and mat2 values
main = "Correlation", # heat map title
notecol="black", # change font color of cell labels to black
notecex=0.5, # change the scaling of the cell labels
density.info="none", # turns off density plot inside color legend
trace="none", # turns off trace lines inside the heat map
margins =c(12,9), # widens margins around plot
col=my_palette, # use on color palette defined earlier
dendrogram="row", # don't draw a row dendrogram
Colv="NA", # turn off column clustering
add.expr = {makeRects(mat2,"black")}) #add the borders
I think something is wrong either with the makeRects function, or with the re-ordering of the rows via the heatmap.2 function. The rectangles appear in the heatmap, but they are not at the right positions. I have been scratching my head all day without finding what is wrong.
Any suggestions?
I would like to plot a raster containing 4 different values (1) with a categorical text legend describing the categories such as 2 but with colour boxes:
I've tried using legend such as :
legend( 1,-20,legend = c("land","ocean/lake", "rivers","water bodies"))
but I don't know how to associate one value to the displayed color. Is there a way to retrieve the colour displayed with 'plot' and to use it in the legend?
The rasterVis package includes a Raster method for levelplot(), which plots categorical variables and produces an appropriate legend:
library(raster)
library(rasterVis)
## Example data
r <- raster(ncol=4, nrow=2)
r[] <- sample(1:4, size=ncell(r), replace=TRUE)
r <- as.factor(r)
## Add a landcover column to the Raster Attribute Table
rat <- levels(r)[[1]]
rat[["landcover"]] <- c("land","ocean/lake", "rivers","water bodies")
levels(r) <- rat
## Plot
levelplot(r, col.regions=rev(terrain.colors(4)), xlab="", ylab="")
By default, the colours used in a raster-plot are generated by rev(terrain.colors()) (see ?raster::plot). You can use this to re-create that sequence of 4 colours for your legend - or choose a random sequence of colours:
my_col = rev(terrain.colors(n = 4))
# my_col = c('beige','red','green','blue')
First plot the map using the colour sequence. legend = FALSE gets rid of the standard colour bar:
plot(my_raster, legend = FALSE, col = my_col)
Add a custom legend to the bottom left. Use the fill argument to generate coloured boxes:
legend(x='bottomleft', legend = c("land", "ocean/lake", "rivers", "water bodies"), fill = my_col)