add text on heatmap using locator() - r

I'm creating an heatmap through heatmap.2(). I'd like to put the xaxis labels rotate of 45 degree. Following the instructions in other posts, I tried to do this building an heatmap without x labels and then using text() to add them...
This is what I tried:
#fake matrix
cheese.matrix <- matrix(runif(100),10,10)
#build color palette
my.palette <- colorRampPalette(c("blue", "green", "yellow", "orange", "red"), space="rgb")
#build a first heatmap
hm_cheese <- heatmap.2(cheese.matrix,Rowv=NA,Colv=NA,col=my.palette,
density.info=c("none"),margins(3,5),cexRow=0.8,
cexCol=0.8,key=TRUE,keysize=1,trace="none",
lhei=c(2,8), breaks=100)
#find the coordinates on the plot where I want to pu the first and the last label
pos2 <- locator()
pos2
$x
[1] 0.08129779 0.90164993
$y
[1] -0.06905376 -0.06372554
pos2 <- structure(list(x=c(0.08129779, 0.90164993), y=c(-0.06905376, -0.06372554)), .Names=c("x","y"))
#create a vector with the labels I want to add
labs <- c("NWC1.PR", "CURD1.PR", "NWC2.PR","CURD2.PR","NWC3.PR","CURD3.PR", "NWC4.PR", "CURD4.PR", "NWC5.PR", "CURD5.PR")
#build another heatmap
hm_cheese <- heatmap.2(cheese.matrix,Rowv=NA,Colv=NA,col=my.palette,
density.info=c("none"),margins(3,5),key=TRUE,
keysize=1,trace="none", lhei=c(2,8), breaks=100,
labCol="", add.expr=text(x=seq(pos2$x[1], pos2$x[2], len=10),
y=rep(pos2$y[1],10), srt=45, xpd=TRUE, adj=0, labels=labs))
This put the labels on the heatmap, but all the names were overlying...
I also tried this:
hm_cheese2 <-heatmap.2(cheese.matrix,Rowv=NA,Colv=NA,col=my.palette,
density.info=c("none"),margins(3,5),key=TRUE,keysize=1,
trace="none", lhei=c(2,8), breaks=100, labCol="",
add.expr=text(x=seq_along(labs), y=-0.06372554, srt=45,
xpd=TRUE, adj=0, labels=labs))
The result was better, since the labels were along the axis, but still really close among them and overlying the plot...
Is there anything wrong in the way I used locator() to find the coordinates?
Can anyone help me to improve my code?

You can play with argument pos in your call to text. By using pos=1 for example:
hm_cheese2 <-heatmap.2(cheese.matrix,Rowv=NA,Colv=NA,col=my.palette,
density.info=c("none"),margins(3,5),key=TRUE,keysize=1,
trace="none", lhei=c(2,8), breaks=100, labCol="",
add.expr=text(x=seq_along(labs), y=-0.06372554, srt=45,
xpd=TRUE, adj=0, labels=labs, pos=1))
See ?text for more on pos.
If the labels fall outside the plot, you can try using xpd=NA to clip them to the device region instead of the plot or the figure regions.
hm_cheese2 <-heatmap.2(cheese.matrix,Rowv=NA,Colv=NA,col=my.palette,
density.info=c("none"),margins(3,5),key=TRUE,keysize=1,
trace="none", lhei=c(2,8), breaks=100, labCol="",
add.expr=text(x=seq_along(labs), y=-0.06372554, srt=45,
xpd=NA, adj=0, labels=labs, pos=1))

Related

How do I find the correct coordinates to align labels with barplot bars?

I'm creating a graphic that has a few different graph elements, using layout() to define plotting regions. I have a separate region for labels that need to align to bars on a barplot in an adjacent plotting region.
I can take a guess at where to plot the labels so that they line up - but the number of these locations will vary so this is not an ideal solution.
Here's an example of what I'm trying to do:
labs <- paste("Some text", letters[1:9])
datA <- table(sample(letters[1:9], size=200, replace=TRUE, prob=rep(c(0.1,0.2,0.3),3)))
layout(matrix(c(1,2,3,3), 2, 2, byrow=TRUE), widths=c(1,2), heights=c(6,1))
plot.new()
text(x=1, y=seq(0.05,1.0,0.111), labels=labs, adj=1, cex=1.4)
barplot(datA, horiz=TRUE, las=1, axes=F, yaxt="n")
How can I find the correct values to plot the labels?
(I'm aware that it looks like this can be solved by just plotting the labels with the barplot - this is not a viable solution for what I'm doing).
The output of barplot gives the heights so:
bp <- barplot(datA, horiz=TRUE, las=1, axes=F, yaxt="n")
text(0*bp, bp, labs, col = "blue", pos = 4)

Overlapping histograms on one page in R

I am a beginner with R. I managed to plot my data into overlapping histograms. However, I would like to place all the histograms on one page. I am struggling as I am not able to tell R, which sets to pick (only manage to plot one of the plots).
This is the code:
df<-read.csv("Salt dshalo sizes.csv",header=T)
#View(df)
library(ggplot2)
DSA<-df[,1]
DS1<-df[,2]
DSB<-df[,5]
DS2<-df[,6]
DSC<-df[,9]
DS3<-df[,10]
#remove the NA column by columns separately or it will chop the data
DSA=na.omit(DSA)
DS1=na.omit(DS1)
DSB=na.omit(DSB)
DS2=na.omit(DS2)
DSC=na.omit(DSC)
DS3=na.omit(DS3)
#plot histograms for DSA, DSB and DSC on one same graph
hist(DSA, prob=TRUE, main="Controls", xlab="Sizes (um)", ylab="Frequency", col="yellowgreen",xlim= c(5,25), ylim=c(0,0.5), breaks=10)
hist(DSB, prob=TRUE, col=rgb(0,0,1,0.5),add=T)
hist(DSC, prob=TRUE, col=rgb(0.8,0,1,0.5),add=T)
#add a legend to the histogram
legend("topright", c("Control 1", "Control2", "Control3"), text.width=c(1,1,1),lwd=c(2,2,2),
col=c(col="yellowgreen", col="blue", col="pink",cex= 1))
box()
#plot histograms for DS1, DS2 and DS3 on one same graph
hist(DS1, prob=TRUE, main="Monoculture Stressed", xlab="Sizes (um)", ylab="Frequency", col="yellowgreen",xlim= c(5,25), ylim=c(0,0.5), breaks=10)
hist(DS2, prob=TRUE, col=rgb(0,0,1,0.5),add=T)
hist(DS3, prob=TRUE, col=rgb(0.8,0,1,0.5),add=T)
#add a legend to the histogram
legend("topright", c("DS1", "DS2", "DS3"), text.width=c(1,1,1),lwd=c(2,2,2),
col=c(col="yellowgreen", col="blue", col="pink",cex= 1))
box()
# put both overlapping histograms onto one page
combined <- par(mfrow=c(1, 2))
plot(hist(DSA),main="Controls")
plot(hist(DS1),main="Monoculture stressed")
par(combined)
Basically, I get two separate overlapping histograms, but cannot put them on the same page.
EDIT: I evidently didn't read your question thoroughly. I see you figured out the add =T.
I assume what you are looking for then is the comment I made first:
par(mfrow = c(a,b)) where a and b are the number of rows and columns you want the graphics objects to be printed. I used c(2,2) for this pic.
I made a comment, but sounds like you may be talking about the add=T option.
a=rnorm(100, 2, 1)
b=rnorm(100, 4, 1)
hist(a, xlim=c(0,10), col="yellow")
hist(b, add=T, col="purple" )
you can play around with transparency options on colors to see both overlap. Such as rgb(1,0,0,1/4) as the color.
With transparency colors:
a=rnorm(100, 2, 1)
b=rnorm(100, 4, 1)
hist(a, xlim=c(0,10), col=rgb(1,1,0,1/4))
hist(b, add=T, col=rgb(1,0,0,1/4) )

Match label with color in raster colorbar

I would like to match colorbar labels with colors in a map when plotting raster objects in R.
Assume I have the following raster:
library(raster)
r <- raster(matrix(runif(100), ncol=10))
and another raster:
r2 <- r/2
brks <- seq(0, 1, by=0.1)
nb <- length(brks)-1
cols <- rev(terrain.colors(nb))
par(mfrow=c(1,2))
plot(r, breaks=brks, col=cols, lab.breaks=brks, zlim=c(0,1), main='first')
plot(r2, breaks=brks, col=cols, lab.breaks=brks, zlim=c(0,1), main='second')
Problem:
If I plot:
plot(r, add=TRUE, legend=FALSE, axes=FALSE, lab.breaks=brks,
zlim=c(0,1), main='first',
col=colorRampPalette(c("darkred", "red3", "orange", "gold1", "yellow",
"lightskyblue","steelblue3", "royalblue3",
"darkblue","darkblue"))(255))
and then intend to plot r2 and I know:
breaks <- seq(min(minValue(r)), max(maxValue(r))))
How can I define values for r and r2 such that they match the colors defined by col above?
Please plot r and r2 with the same colorbar scale and assign values of choice to match those colors on the map. The values on the map must not necessarily be those assigned to the colorbar.
I need this kind of exercise because I am doing interpolation of station data. Kriging gives a good looking raster but underestimates the values. However, I have the max and min of the data I am mapping. Using the colors in col as above, I would like to assign values to the colorbar based on the colors on the map.
Many thanks,
Asong.

Texture in barplot for 7 bars in R?

I have 7 different categories per each value in X. I am using barplot to plot these categories. Such graph looks fine in colors printer, but what if I want it to be fine in black & white. You can check the graph below. I want to have different colors texture, so the graph looks good in color and black & white printer.
I used densities = c(10,30,40,50,100,60,80) for density parameter in barplot function. Are there any other ways to do different texture in barplot?
Note: I tried the angle value in barplot. However, it isn't a good solution in that case, since not all bars have high values (i.e height of the bar).
Along the lines of my comment, you might find the following helpful:
# data generation ---------------------------------------------------------
set.seed(1)
mat <- matrix(runif(4*7, min=0, max=10), 7, 4)
rownames(mat) <- 1:7
colnames(mat) <- LETTERS[1:4]
# plotting settings -------------------------------------------------------
ylim <- range(mat)*c(1,1.5)
angle1 <- rep(c(45,45,135), length.out=7)
angle2 <- rep(c(45,135,135), length.out=7)
density1 <- seq(5,35,length.out=7)
density2 <- seq(5,35,length.out=7)
col <- 1 # rainbow(7)
# plot --------------------------------------------------------------------
op <- par(mar=c(3,3,1,1))
barplot(mat, beside=TRUE, ylim=ylim, col=col, angle=angle1, density=density1)
barplot(mat, add=TRUE, beside=TRUE, ylim=ylim, col=col, angle=angle2, density=density2)
legend("top", legend=1:7, ncol=7, fill=TRUE, col=col, angle=angle1, density=density1)
par(bg="transparent")
legend("top", legend=1:7, ncol=7, fill=TRUE, col=col, angle=angle2, density=density2)
par(op)

R - Common title and legend for combined plots

I would like to know how to provide a common title and legend for combined plots in R. I have four plots which I have combined into one. Each plot has its own Title. I want to specify a common Title on the top center and common legend on the top left corner of the combined plot. I generated the combined plot using par(). I have provided my plot below
You can use the oma parameter to increase the outer margins,
then add the main title with mtext,
and try to position the legend by hand.
op <- par(
oma=c(0,0,3,0),# Room for the title and legend
mfrow=c(2,2)
)
for(i in 1:4) {
plot( cumsum(rnorm(100)), type="l", lwd=3,
col=c("navy","orange")[ 1+i%%2 ],
las=1, ylab="Value",
main=paste("Random data", i) )
}
par(op) # Leave the last plot
mtext("Main title", line=2, font=2, cex=1.2)
op <- par(usr=c(0,1,0,1), # Reset the coordinates
xpd=NA) # Allow plotting outside the plot region
legend(-.1,1.15, # Find suitable coordinates by trial and error
c("one", "two"), lty=1, lwd=3, col=c("navy", "orange"), box.col=NA)

Resources