Change transparency of points in a legend - r

I have plotted a network plot with igraph. The opacity of the vertices is reduced to 0.5.
Now I would like to add a legend to the plot manually, where the points have the same color/transparency as the vertices in the plot.
plot(g, vertex.color = adjustcolor(V(g)$color, alpha = 0.5))
legend('topleft',legend = names, pt.cex = 2, pch = 21, pt.bg = colors)
How can I alter the transparency of the points in the legend?

Since you do not provide data, I make up some sample data. Also, both "names" and "colors" are the names of R functions so I changed them to "Names" and "Colors".
You can make the adjustment that you want just by using adjustcolor again.
library(igraph)
## Some sample data
set.seed(1234)
g = erdos.renyi.game(10, 0.3)
Colors = rainbow(4)
V(g)$color = sample(Colors,10, replace=TRUE)
Names = paste("N", 1:4, sep="")
## Your plot and adjusted legend
plot(g, vertex.color = adjustcolor(V(g)$color, alpha = 0.5))
legend('topleft', legend = Names, pt.cex = 2, pch = 21,
pt.bg = adjustcolor(Colors, alpha = 0.5))

Related

How can I change the colour of my points on my db-RDA triplot in R?

QUESTION: I am building a triplot for the results of my distance-based RDA in R, library(vegan). I can get a triplot to build, but can't figure out how to make the colours of my sites different based on their location. Code below.
#running the db-RDA
spe.rda.signif=capscale(species~canopy+gmpatch+site+year+Condition(pair), data=env, dist="bray")
#extract % explained by first 2 axes
perc <- round(100*(summary(spe.rda.signif)$cont$importance[2, 1:2]), 2)
#extract scores (coordinates in RDA space)
sc_si <- scores(spe.rda.signif, display="sites", choices=c(1,2), scaling=1)
sc_sp <- scores(spe.rda.signif, display="species", choices=c(1,2), scaling=1)
sc_bp <- scores(spe.rda.signif, display="bp", choices=c(1, 2), scaling=1)
#These are my location or site names that I want to use to define the colours of my points
site_names <-env$site
site_names
#set up blank plot with scaling, axes, and labels
plot(spe.rda.signif,
scaling = 1,
type = "none",
frame = FALSE,
xlim = c(-1,1),
ylim = c(-1,1),
main = "Triplot db-RDA - scaling 1",
xlab = paste0("db-RDA1 (", perc[1], "%)"),
ylab = paste0("db-RDA2 (", perc[2], "%)")
)
#add points for site scores - these are the ones that I want to be two different colours based on the labels in the original data, i.e., env$site or site_names defined above. I have copied the current state of the graph
points(sc_si,
pch = 21, # set shape (here, circle with a fill colour)
col = "black", # outline colour
bg = "steelblue", # fill colour
cex = 1.2) # size
Current graph
I am able to add species names and arrows for environmental predictors, but am just stuck on how to change the colour of the site points to reflect their location (I have two locations defined in my original data). I can get them labelled with text, but that is messy.
Any help appreciated!
I have tried separating shape or colour of point by site_name, but no luck.
If you only have a few groups (in your case, two), you could make the group a factor (within the plot call). In R, factors are represented as an integer "behind the scenes" - you can represent up to 8 colors in base R using a simple integer:
set.seed(123)
df <- data.frame(xvals = runif(100),
yvals = runif(100),
group = sample(c("A", "B"), 100, replace = TRUE))
plot(df[1:2], pch = 21, bg = as.factor(df$group),
bty = "n", xlim = c(-1, 2), ylim = c(-1, 2))
legend("topright", unique(df$group), pch = 21,
pt.bg = unique(as.factor(df$group)), bty = "n")
If you have more than 8 groups, or if you would like to define your own colors, you can simply create a vector of colors the length of your groups and still use the same factor method, though with a few slight tweaks:
# data with 10 groups
set.seed(123)
df <- data.frame(xvals = runif(100),
yvals = runif(100),
group = sample(LETTERS[1:10], 100, replace = TRUE))
# 10 group colors
ccols <- c("red", "orange", "blue", "steelblue", "maroon",
"purple", "green", "lightgreen", "salmon", "yellow")
plot(df[1:2], pch = 21, bg = ccols[as.factor(df$group)],
bty = "n", xlim = c(-1, 2), ylim = c(-1, 2))
legend("topright", unique(df$group), pch = 21,
pt.bg = ccols[unique(as.factor(df$group))], bty = "n")
For pch just a slight tweak to wrap it in as.numeric:
pchh <- c(21, 22)
ccols <- c("slateblue", "maroon")
plot(df[1:2], pch = pchh[as.numeric(as.factor(df$group))], bg = ccols[as.factor(df$group)],
bty = "n", xlim = c(-1, 2), ylim = c(-1, 2))
legend("topright", unique(df$group),
pch = pchh[unique(as.numeric(as.factor(df$group)))],
pt.bg = ccols[unique(as.factor(df$group))], bty = "n")

How to add centroids to an RDA plot

I'd like to replace the arrows on this RDA plot with centroids, something like what's pictured here.
This is the code I currently have which provides me arrows (I guess by default). I have shared our RDA code and I think this is where we might be able to change it from arrows to centroid:
# add arrows for effects of the expanatory variables
arrows(0,0, # start them from (0,0)
sc_bp[,1], sc_bp[,2], # end them at the score value
col = "red",
lwd = 1,
length = .1)
(but I share the entire code chunk (below), just in case.
Please note that my data is on fish community (species) and substrate types at 36 sites, I'd like to replace the arrows for substrates with centroids within my RDA.
##Now, the RDA
Y.mat<-Belt_2021_fish_transformed_forPCA #fish community
str(Y.mat)
X.mat<-Reefcheck_2021_forPCA #substrate
str(X.mat)
###Community data has already been transformed with hellinger
##Now, try the RDA
fish_substrate_rda<-rda(Y.mat,X.mat)
```
##Plot
## extract % explained by the first 2 axes
perc_b <- round(100*(summary(fish_substrate_rda)$cont$importance[2, 1:2]), 2)
## extract scores - these are coordinates in the RDA space
sc_si <- scores(fish_substrate_rda, display="sites", choices=c(1,2), scaling=1)
sc_sp <- scores(fish_substrate_rda, display="species", choices=c(1,2), scaling=1)
sc_sp <- sc_sp[c(2,7,8),]
sc_bp <- scores(fish_substrate_rda, display="bp", choices=c(1,2), scaling=1)
sc_bp <- sc_bp[c(2,5,6),]
# Set up a blank plot with scaling, axes, and labels
plot(fish_substrate_rda,
scaling = 1, # set scaling type
type = "none", # this excludes the plotting of any points from the results
frame = TRUE,
# set axis limits
ylim = c(-1.5,0.7),
xlim = c(-1.5,1.2),
# label the plot (title, and axes)
main = "Triplot RDA - scaling 1",
xlab = paste0("RDA1 (", perc_b[1], "%)"),
ylab = paste0("RDA2 (", perc_b[2], "%)")
)
# add points for site scores
points(sc_si,
pch = 21, # set shape (here, circle with a fill colour)
col = "black", # outline colour
bg = "steelblue", # fill colour
cex = 0.7) # size
# add points for species scores
points(sc_sp,
pch = 22, # set shape (here, square with a fill colour)
col = "black",
bg = "#f2bd33",
cex = 0.7)
# add text labels for species abbreviations
text(sc_sp + c(-0.09, -0.09), # adjust text coordinates to avoid overlap with points
labels = rownames(sc_sp),
col = "grey40",
font = 2, # bold
cex = 0.6)
# add arrows for effects of the expanatory variables
arrows(0,0, # start them from (0,0)
sc_bp[,1], sc_bp[,2], # end them at the score value
col = "red",
lwd = 1,
length = .1)
# add text labels for arrows
text(x = sc_bp[,1] -0.01, # adjust text coordinate to avoid overlap with arrow tip
y = sc_bp[,2] - 0.09,
labels = rownames(sc_bp),
col = "red",
cex = .7,
font = 1)
```
I have not found anything online that might help me to accomplish this.

Moving legend outside of plot area (Vegan package)

I'm trying to use vegan package in R to create NMDS plots for my research. I'm having problems placing the legend in the correct area, however. The legend always covers some of the points and gets cut off by the outline of the plot. Anyone have any ideas of how I could format the legend outside of the plot area, or move it so that it doesn't cover up any points?
Here is an exported image of what my graph looks like now, with part of the legend missing and covering up some points.
Here is the script I've been using:
op <- ordiplot(nmds, type = 'n')
cols = c('darkred', 'darkgreen', 'darkblue', 'yellow', 'pink', 'lightgreen', 'lightblue', 'black')
points(nmds, cex = 2, pch = 16, col = cols[coral_ENV$Year])
ordispider(nmds, groups = coral_ENV$Year, label = TRUE, label.size = 0.2)
ordihull(nmds, groups = coral_ENV$Year, lty = 'dotted')
legend("topleft", inset = 0.03, pch = 16, col = cols, text.width = 0.05, legend = levels(coral_ENV$Year))
I'm pretty new to R so I'd appreciate any help!

Network plot colors do not match legend

I have an igraph network which I want to color with RColorBrewer. Vertices have a "sector" attribute, which I want to use to color them. To do this, I have defined a color palette based on sectors:
color.range <- brewer.pal(nlevels(as.factor(V(g)$sector)), name = "Dark2")
V(g)$color <- color.range[as.factor(V(g)$sector)]
When I plot my graph, colors of the legend do not match the information in the "sector" attribute of my vertices:
plot.igraph(g,
vertex.label = ifelse(V(g)$indegree > 5, V(g)$sector, NA),
vertex.label.family = "Arial",
vertex.label.color = "black",
vertex.label.cex = 0.5,
vertex.frame.color = NA,
vertex.color = V(g)$color,
vertex.size = 3,
layout = layout.fruchterman.reingold,
edge.arrow.mode = 1,
edge.arrow.size = 0.2)
legend("topleft",
legend = levels(as.factor(V(g)$sector)),
col = levels(as.factor(V(g)$color)),
pch = 19,
cex = 0.8,
title = "",
bg="transparent",
bty = "n")
On the plot I see the categories of some high degree vertices and comparing them with the legend, colors do not match:
example plot where colors on graph do not match legend
My question is: how can I define a color range that will actually match my sector categories OR how can I create a legend that represents colors properly. Unfortunately I don't know which one is the problem.
I think that you are computing the colors for the legend incorrectly. If instead, I use
col = color.range[as.numeric(levels(as.factor(V(g)$sector)))]
the colors in the legend match the labeled points in the graph.
For me the solution of G5W as not completely working as
levels(as.factor(V(g)$sector))
returned the levels as a list of strings that could not be turned into numbers, so I have got an error:
Warning message:
In legend("topleft",legend = levels(as.factor(V(g)$sector)),col =
color.range[as.numeric(levels(as.factor(V(g)$sector)))],: NAs introduced by coercion
I have added one more as.factor() instead and it seems to work now:
col = color.range[as.numeric(as.factor(levels(as.factor(V(g)$sector))))],

How to make R legend with 2 columns?

I want to make a legend on my graph, which is generated by plot() function. The original legend() function will generate a list which has only 1 column. How can I make a legend which has 2 columns?
I could not find a way to do that within a single call to legend for standard plots.
Here's an option, drawing two separate legends: one with lines and points, one with labels. x.intersp can be used to tweak distance between labels and lines.
plot(cumsum(runif(n = 100)))
# draw legend with lines and point but without labels and box. x.intersp controls horizontal distance between lines
L = legend(x = 'bottom', legend = rep(NA,4), col=1:2, lty=c(1,1,2,2), ncol=2, bty='n', x.intersp=0.5, pch=c(1,2,1,2), inset=0.02)
# use position data of previous legend to draw legend with invisble lines and points but with labels and box. x.intersp controls distance between lines and labels
legend(x = L$rect$left, y = L$rect$top, legend = c('Group A', 'Group B'), col=rep(NA,2), lty=c(1,1), ncol=1, x.intersp = 3, bg = NA)
Check this:
library(lattice)
myPCH <- 15:17
Data <- rnorm(50)
Index <- seq(length(Data))
xyplot(Data ~ Index,
pch = myPCH, col=1:2,
key = list(space = "right", adj=1,
text = list(c("a", "b", "c"), cex=1.5),
points = list(pch = myPCH),
points = list(pch = myPCH,col=2)))
It looks like Victorp answered this in the comments of the original post. The ncol argument in the legend function works for me:
legend(locator(1), legend=c("name1","name2", "name3", "name4"), lty=2, col=c("black", "blue", "dark green", "orange"), ncol=2)
enter image description here

Resources