R - draw new layer behind current plot - r

Just curious, when plotting in R, one can easily change the order of the executive code to change the order of those "layer" on the plot, e.g.
plot(x, type = "n")
lines(y)
points(x)
to get x over the y. Are there any way to do it in an adhoc way, e.g.
plot(x)
lines(y, behind = TRUE) # fictional option behind

While there isn't explicitly a behind option or layers in plot, an easy way to overlay two plots might be using the add = TRUE option in plot. Here is an example with artificial data:
# Load sp package for creating artificial data
library(sp)
# Create sample town points
towns <- data.frame(lon = sample(100), lat = sample(100))
towns <- SpatialPoints(towns)
# Create sample polygon grid
grd <- GridTopology(c(1,1), c(10,10), c(10,10))
polys <- as.SpatialPolygons.GridTopology(grd)
# Plot polygons
plot(polys)
# Add towns (in red colour)
plot(towns, add = TRUE, col = 'red')
As another example, you can plot lines on different layers in ggplot and melt like this:
a <- c(3, 6, 16, 17, 11, 21)
b <- c(0.3, 2.3, 9, 9, 5 ,12)
c <- c(3, 7, 9, 7, 6, 10)
dat <- data.frame(a=a,b=b,c=c)
dat <- melt(dat)
Add an explicit 'x' variable to our data frame:
dat$x <- rep(1:6,times=3)
Then just plot the graph:
ggplot(dat,aes(x=x,y=value)) +
geom_line(aes(colour=variable)) +
scale_colour_manual(values=colours) +
labs(x="time[h]",y="a",colour="") +
opts(title="bla")
Finally, there is explicit support for layers in other packages, such as in PBSmapping for maps.

Related

Formatting phylogeny to map projection (`phylo.to.plot`, or alternate method) in R

I am hoping someone can help me with the formating from phylo.to.plot() or suggest another method that can produce a similar output.
I have followed tutorial(s) here to produce an output but it seems difficult to alter the resulting figures.
Briefly these are my questions. I will expand further below.
How to plot a subregion of a "WorldHires" map, not entire region?
Change the shape of the points on the map, but maintain the colour?
Add gradient of continuous variable to map
Reproducible example:
Here is a very basic tree with some randomly assigned geographic locations
myTree <- ape::read.tree(text='((A, B), ((C, D), (E, F)));')
plot(myTree)
# It needs to be rooted for `phylo.to.map()` to work
myTree$branch.length = NULL
rooted_cladogram = ape::compute.brlen(myTree)
# Sample information
Sample <- c("A","B","C","D","E","F")
coords <- matrix(c(56.001966,57.069417,50.70228, 51.836213, 54.678997, 54.67831,-5.636926,-2.47805,-3.8975018, -2.235444,-3.4392211, -1.751833), nrow=6, ncol=2)
rownames(coords) <- Sample
head(coords)
## Plot phylo.to.map
obj<-phylo.to.map(rooted_cladogram,coords,database="worldHires", regions="UK",plot=FALSE,xlim=c(-11,3), ylim=c(49,59),direction="rightwards")
plot(obj,direction="rightwards",fsize=0.5,cex.points=c(0,1), lwd=c(3,1),ftype="i")
Plot output here:
Question 1: How do I plot a subregion of a "WorldHires" map, not the entire region?
I would like to only have mainland Britain which is a subregion of the "UK" in the WorldHires database. To access it normally I would do:
map1 <- ggplot2::map_data(map = "worldHires", region = c("UK"),xlim=c(-11,3), ylim=c(49,59))
GB <- subset(map1, subregion=="Great Britain")
# Plot
GB_plot<- ggplot(GB )+
geom_polygon(aes(x = long, y = lat, group = group), fill = "white", colour = "black")+
theme_classic()+
theme(axis.line=element_blank(),
axis.text=element_blank(),
axis.ticks=element_blank(),
axis.title=element_blank(),
panel.border = element_blank())
Which looks like this:
I have tried but it ignore the subregion argument.
obj<-phylo.to.map(ttree,coords,database="worldHires", regions="UK", subregion="Great Britain",plot=FALSE,xlim=c(-11,3), ylim=c(49,59),direction="rightwards")
Is there a way to provide it directly with a map instead of using WorldHires?
Question 2: How do I change the shape of the points on the map but keep maintain the colour?
I want to use shapes on the map to indicate the 3 major clade on my tree geographically. However, when I add a pch argument in, it correctly changes the shapes but the points then become black instead of following the colour that they were before. The lines from the tree to the map maintain the colour, it is just the points themselves that seem to turn black.
This is how I have tried to change the shape of the points:
# Original code - points
cols <-setNames(colorRampPalette(RColorBrewer::brewer.pal(n=6, name="Dark2"))(Ntip(myTree)),myTree$tip.label)
obj<-phylo.to.map(rooted_cladogram,coords,database="worldHires", regions="UK",plot=FALSE,xlim=c(-11,3), ylim=c(49,59),direction="rightwards")
plot(obj,direction="rightwards",fsize=0.5,cex.points=c(0,1), colors=cols,lwd=c(3,1),ftype="i")
Point and lines are coloured. I would like to change the shape of points
# Code to change points = but points are no longer coloured
shapes <- c(rep(2,2),rep(1,2),rep(0,2))
obj<-phylo.to.map(rooted_cladogram,coords,database="worldHires", regions="UK",plot=FALSE,xlim=c(-11,3), ylim=c(49,59),direction="rightwards")
plot(obj,direction="rightwards",fsize=0.5,cex.points=c(0,1), colors=cols,pch=shapes,lwd=c(3,1),ftype="i")
Output: The shapes are changed but they are no longer coloured in:
Question 3: How do I add a gradient to the map?
Given this fake dataset, how to I create a smoothed gradient of the value variable?
Any help and advice on this would be very much appreciated.
It would also be useful to know how to change the size of points
Thank you very much in advance,
Eve
I improved (somewhat) on my comments by using the map you made in your question. Here's the code:
library(mapdata)
library(phytools)
library(ggplot2)
myTree <- ape::read.tree(text='((A, B), ((C, D), (E, F)));')
plot(myTree)
# It needs to be rooted for `phylo.to.map()` to work
myTree$branch.length = NULL
rooted_cladogram = ape::compute.brlen(myTree)
# Sample information
Sample <- c("A","B","C","D","E","F")
coords <- matrix(
c(56.001966,
57.069417,
50.70228,
51.836213,
54.678997,
54.67831,
-5.636926,
-2.47805,
-3.8975018,
-2.235444,
-3.4392211,
-1.751833),
nrow=6,
ncol=2)
rownames(coords) <- Sample
head(coords)
obj <- phylo.to.map(
rooted_cladogram,
coords,
database="worldHires",
regions="UK",
plot=FALSE,
xlim=c(-11,3),
ylim=c(49,59),
direction="rightwards")
# Disable default map
obj2 <- obj
obj2$map$x <- obj$map$x[1]
obj2$map$y <- obj$map$y[1]
# Set plot parameters
cols <- setNames(
colorRampPalette(
RColorBrewer::brewer.pal(n=6, name="Dark2"))(Ntip(myTree)),myTree$tip.label)
shapes <- c(rep(2,2),rep(1,2),rep(0,2))
sizes <- c(1, 2, 3, 4, 5, 6)
# Plot phylomap
plot(
obj2,
direction="rightwards",
fsize=0.5,
cex.points=0,
colors=cols,
pch=shapes,
lwd=c(3,1),
ftype="i")
# Plot new map area that only includes GB
uk <- map_data(
map = "worldHires",
region = "UK")
gb <- uk[uk$subregion == "Great Britain",]
points(x = gb$long,
y = gb$lat,
cex = 0.001)
# Plot points on map
points(
x = coords[,2],
y = coords[,1],
pch = shapes,
col = cols,
cex = sizes)
e: Use sf object instead of points to illustrate GB. It is tough to provide more advice beyond this on how to add symbology for your spatially varying variable, but sf is popular and very well documented, e.g. https://r-spatial.github.io/sf/articles/sf5.html. Let me know if you have any other questions!
ee: Added lines to plot name and symbol on tips.
eee: Added gradient dataset to map.
library(phytools)
library(mapdata)
library(ggplot2)
library(sf)
myTree <- ape::read.tree(text='((A, B), ((C, D), (E, F)));')
plot(myTree)
# It needs to be rooted for `phylo.to.map()` to work
myTree$branch.length = NULL
rooted_cladogram = ape::compute.brlen(myTree)
# Sample information
Sample <- c("A","B","C","D","E","F")
coords <- matrix(c(56.001966,57.069417,50.70228, 51.836213, 54.678997, 54.67831,-5.636926,-2.47805,-3.8975018, -2.235444,-3.4392211, -1.751833), nrow=6, ncol=2)
rownames(coords) <- Sample
head(coords)
obj <- phylo.to.map(
rooted_cladogram,
coords,
database="worldHires",
regions="UK",
plot=FALSE,
xlim=c(-11,3),
ylim=c(49,59),
direction="rightwards")
# Disable default map
obj2 <- obj
obj2$map$x <- obj$map$x[1]
obj2$map$y <- obj$map$y[1]
## Plot tree portion of map
# Set plot parameters
cols <- setNames(
colorRampPalette(
RColorBrewer::brewer.pal(n=6, name="Dark2"))(Ntip(myTree)),myTree$tip.label)
shapes <- c(rep(2,2),rep(1,2),rep(0,2))
sizes <- c(1, 2, 3, 4, 5, 6)
# Plot phylomap
plot(
obj2,
direction="rightwards",
fsize=0.5,
cex.points=0,
colors=cols,
pch=shapes,
lwd=c(3,1),
ftype="i")
tiplabels(pch=shapes, col=cols, cex=0.7, offset = 0.2)
tiplabels(text=myTree$tip.label, col=cols, cex=0.7, bg = NA, frame = NA, offset = 0.2)
## Plot GB portion of map
# Plot new map area that only includes GB
uk <- map_data(map = "worldHires", region = "UK")
gb <- uk[uk$subregion == "Great Britain",]
# Convert GB to sf object
gb_sf <- st_as_sf(gb, coords = c("long", "lat"))
# Covert to polygon
gb_poly <- st_sf(
aggregate(
x = gb_sf$geometry,
by = list(gb_sf$region),
FUN = function(x){st_cast(st_combine(x), "POLYGON")}))
# Add polygon to map
plot(gb_poly, col = NA, add = TRUE)
## Load and format gradient data as sf object
# Load data
g <- read.csv("gradient_data.txt", sep = " ", na.strings = c("NA", " "))
# Check for, then remove NAs
table(is.na(g))
g2 <- g[!is.na(g$Lng),]
# For demonstration purposes, make dataset easier to manage
# Delete this sampling line to use the full dataset
g2 <- g2[sample(1:nrow(g2), size = 1000),]
# Create sf point object
gpt <- st_as_sf(g2, coords = c("Lng", "Lat"))
## Set symbology and plot
# Cut data into 5 groups based on "value"
groups <- cut(gpt$value,
breaks = seq(min(gpt$value), max(gpt$value), len = 5),
include.lowest = TRUE)
# Set colors
gpt$colors <- colorRampPalette(c("yellow", "red"))(5)[groups]
# Plot
plot(gpt$geometry, pch = 16, col = gpt$colors, add = TRUE)
## Optional legend for gradient data
# Order labels and colors for the legend
lev <- levels(groups)
# Used rev() here to make colors in correct order
fil <- rev(levels(as.factor(gpt$colors)))
legend("topright", legend = lev, fill = fil, add = TRUE)
## Plot sample points on GB
# Plot points on map
points(
x = coords[,2],
y = coords[,1],
pch = shapes,
col = cols,
cex = sizes)
see here for more info on gradient symbology and legends: R: Gradient plot on a shapefile

Clustering plot. Add the cluster number: Function fviz_cluster (factoextra)

I have the following R code:
library(factoextra)
kms<-kmeans(df,18,nstart=100)
fviz_cluster(kms, data = df, alpha=0.2,shape=19,geom = "point")
It outputs the following picture:
Is possible to add the number of the clusters inside the respective cluster in the picture?. Or show the cluster numbers instead fo the point centers.
UPDATE.
Something similar to I want to achieve I found in : https://www.r-bloggers.com/2016/11/hybrid-hierarchical-k-means-clustering-for-optimizing-clustering-outputs-unsupervised-machine-learning/
I tried it, but I got error. So I have to install the version of factoextra that is used and change the code. So I got this:
fviz_cluster(kms, data = df,frame.level = 0.68)
How can i remove the numbers except the numbers on the center of the cluster?
There doesn't seem to be a simple solution; here is a potential workaround:
library(tidyverse)
library(factoextra)
data("iris")
# Select a single point for each category (i.e. setosa = the 25th value)
# label the selected value, then label the rest of the points with nothing ("")
iris$label <- c(rep("", 24), "setosa", rep("", 25),
rep("", 23), "versicolor", rep("", 26),
rep("", 24), "virginica", rep("", 25))
# Remove species column (5) and label column and scale the data
iris.scaled <- scale(iris[, -c(5,6)])
# K-means clustering
km.res <- kmeans(iris.scaled, 3, nstart = 10)
# Visualize clusters
fviz_cluster(km.res, iris[, -c(5,6)], alpha = 0.2, shape = 19, geom = c("point")) +
# Label the points (only the 3 with actual labels show up on the plot)
geom_text(aes(label = iris$label))

Determine "optimal" x coordinates for nodes when plotting dendritic network with pre-determined y coordinates

I am trying to plot a dendritic network (a river network) in R, using the ggnet2 function, and I want the y axis on the plot to be meaningful... specifically I want it to represent the basin area. I am looking for a method, then, that will calculate x coordinates so that the network displays nicely, with no crossing lines. How might I do this? See the code and example images below. In the first image, the y coordinates are specified to equal the area, which is what I want, but the x-coordinates are non-optimized so the graph looks ugly. In the second image, Fruchterman-Rhinegold placement looks great but the y coordinates are obviously arbitrary. I'm not wedded to using ggnet2, but I do want the network links to be angular (e.g. not like a clustering dendrogram with vertical links between nodes). Thanks!
[![library(GGally)
library(network)
library(sna)
graphmatrix <- matrix(c(0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0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net <- network(graphmatrix, directed=TRUE)
layout <- gplot.layout.fruchtermanreingold(wsnet, NULL)
wsnet %v% 'sitenumber' = sitenumbers
wsnet %v% 'area' = areas
wsnet %v% 'randomnumber'= sample(sitenumbers)
ggnet2(wsnet, label='sitenumber')
#You can specify y coordinates, but then you need to also specify x coords, so there's tons of line crossing... I want to "optimize" the x coords.
ggnet2(wsnet, label='sitenumber', mode=c('randomnumber','area'))][1]][1]
Here would be a ggraph solution to the problem. We'll start out by laying out a dendrogram and then tell ggraph to use the area as y positions.
library(tidygraph)
library(ggraph)
gr <- as_tbl_graph(wsnet)
lay <- create_layout(gr, "dendrogram")
lay$y <- lay$area
ggraph(lay) +
geom_edge_link() +
geom_node_point(size = 10, shape = 21, fill = "white") +
geom_node_text(aes(label = sitenumber))
Now obviously this is not perfect with intersecting lines and such, but it's a good starting point. You could tweak some positions manually:
lay$x[lay$sitenumber %in% c(12, 10, 17, 20, 28)] <- lay$x[lay$sitenumber %in% c(12, 10, 17, 20, 28)] + 1
lay$x[lay$sitenumber %in% c(1, 2)] <- lay$x[lay$sitenumber %in% c(1, 2)] - 2
lay$x[lay$sitenumber == 27] <- lay$x[lay$sitenumber == 27] + 2
lay$x[lay$sitenumber == 26] <- lay$x[lay$sitenumber == 26] + 3
ggraph(lay) +
geom_edge_link() +
geom_node_point(size = 10, shape = 21, fill = "white") +
geom_node_text(aes(label = sitenumber))
Adjust flavours to taste.

Dendrogram based on col values in a dataframe using R [duplicate]

I would like to create a dendrogram in R which has colored branches, like the one shown below.
So far I used following commands to create a standard dendrogram:
d <- dist(as.matrix(data[,29])) # find distance matrix
hc <- hclust(d) # apply hirarchical clustering
plot(hc,labels=data[,1], main="", xlab="") # plot the dendrogram
How should I modify this code to obtain desired result ?
Thanks in advance for your help.
You could use the dendextend package, aimed for tasks such as this:
# install the package:
if (!require('dendextend')) install.packages('dendextend'); library('dendextend')
## Example:
dend <- as.dendrogram(hclust(dist(USArrests), "ave"))
d1=color_branches(dend,k=5, col = c(3,1,1,4,1))
plot(d1) # selective coloring of branches :)
d2=color_branches(d1,k=5) # auto-coloring 5 clusters of branches.
plot(d2)
# More examples are in ?color_branches
You can see many examples in the presentations and vignettes of the package, in the "usage" section in the following URL: https://github.com/talgalili/dendextend
You should use dendrapply (help document).
For instance:
# Generate data
set.seed(12345)
desc.1 <- c(rnorm(10, 0, 1), rnorm(20, 10, 4))
desc.2 <- c(rnorm(5, 20, .5), rnorm(5, 5, 1.5), rnorm(20, 10, 2))
desc.3 <- c(rnorm(10, 3, .1), rnorm(15, 6, .2), rnorm(5, 5, .3))
data <- cbind(desc.1, desc.2, desc.3)
# Create dendrogram
d <- dist(data)
hc <- as.dendrogram(hclust(d))
# Function to color branches
colbranches <- function(n, col)
{
a <- attributes(n) # Find the attributes of current node
# Color edges with requested color
attr(n, "edgePar") <- c(a$edgePar, list(col=col, lwd=2))
n # Don't forget to return the node!
}
# Color the first sub-branch of the first branch in red,
# the second sub-branch in orange and the second branch in blue
hc[[1]][[1]] = dendrapply(hc[[1]][[1]], colbranches, "red")
hc[[1]][[2]] = dendrapply(hc[[1]][[2]], colbranches, "orange")
hc[[2]] = dendrapply(hc[[2]], colbranches, "blue")
# Plot
plot(hc)
Which gives:
FigTree can make color dendrograms. See for example, this paper.
To get data into FigTree from an R distance matrix dm,
library(ape)
z <- as.phylo(hclust(as.dist(dm)))
write.nexus(z, file="output.nex")

Set color for NA Value with spplot in R

I'm trying to plot polygon data using function spplot from the sp package, but there are some missing values (NA) in my dataframe. When I plot this dataframe, missing values have a transparent color. I want to plot them in black. How can I do this?
library(sp)
spplot(TestData,12)
Here is my TestData object
One way to achieve this is to use latticeExtra::layer_ to plot all polygons with your preferred NA colour, beneath the standard spplot.
library(latticeExtra)
spplot(TestData, 12, col.regions=heat.colors(101), at=seq(0, 4, length=100)) +
layer_(sp.polygons(TestData, fill='black'))
Similarly, if you have raster data, you can do the same with layer_ and grid.rect:
library(raster)
library(latticeExtra)
r <- raster(matrix(runif(100), ncol=10))
r[sample(100, 10)] <- NA
spplot(r, col.regions=grey.colors, at=seq(0, 1, length=100)) +
layer_(grid.rect(0, 0, 2, 2, gp=gpar(fill = 'lightblue')))
I am using solution similar to jbaums', but I do it directly in the spplot function:
spplot(TestData, 12, col.regions=heat.colors(101), at=seq(0, 4, length=100),
sp.layout = list(
list("sp.polygons", TestData, first = TRUE, fill = "black")
)
)
The sp.layout parameter allows to plot other spatial objects in the plot. So we plot the TestData polygon layer with black fill. The parameter first = TRUE says it is to be plot before the actual data - so it acts as a background.

Resources