How to add a legend to a plot in R - r

I´m new to R. I cannot put a legend in a plot chart, there is someting wrong with my code, I´ve tried to put a legend on this plot. I did a hash to put some colors on my model, but now I can´t figure out how to put the correct legend on it. This is what I di:
myhash<-c(a="green",b="pink",c="blue",d="purple",e="orange",f="brown",g="yellow",
h="black",i="gray")
mycolor<-myhash[df$category]
plot(df$growth,df$tannin,col=mycolor,cex=1,pch=16,xlab="Crecimiento",ylab="Taninos", main = "Modelo lineal Taninos vs Crecimiento")
I tried to put the legend like this :
legend("topright",c(df$tannin),fill=c("green","pink","blue","purple","orange","brown","yellow",
"black","gray"))
Please let me know how can I fix it, Im very beginner in R. Also, I cannot use any library.
Thanks in advance.

The problem seems to be that there is no legend (the argument to function legend, not the function) to show as text beside the fill colors.
To use a named argument, legend = unique(names(mycolor)) solves the problem.
set.seed(2020)
df <- data.frame(category = rep(c("a","b", "c", "d"), 4),
growth = 1:16, tannin = cumsum(rnorm(16)))
myhash <- c(a = "green", b = "pink", c = "blue", d = "purple")
mycolor <- myhash[df$category]
plot(df$growth, df$tannin, col = mycolor, cex = 1, pch = 16,
xlab = "Crecimiento", ylab = "Taninos",
main = "Modelo lineal Taninos vs Crecimiento")
legend("topright", legend = unique(names(mycolor)), fill = mycolor)

Related

Change legend labels in ggcompetingrisks plot in r

I have made a cumulative incidence plot using cmprsk::cuminc and then ggcompetingrisks for plotting.
I want to change legend labels for the group.
I've tried with legend.lab = c("A", "B", "C").
This works when I do a ggsurvplot without competing risk. But it does not work now.
Any suggestions?
My code is like:
fit <- cuminc(df$Time, df$Event, group = df$genotype)
p <- ggcompetingrisks(fit, multiple_panels = FALSE, palette = "black",
legend.title = c("genotype"),
legend.labs = c("A", "B", "C"))
The thing is that the legend show both the Event (0, 1) and the Group (1, 2, 3). I want only the group to be shown in the legend and I want it to be named A, B and C..
Please help me!!
If I get your fit correct, group will be plotted as linetype so you can use scale_linetype_manual() to set the title of the legend, and the names. To turn of the other legend about event, you can use guides()
See below for an example using some simulated data:
library(survminer)
library(ggplot2)
library(cmprsk)
df = data.frame(
Time = rexp(100),
genotype = factor(sample(1:3,100,replace=TRUE)),
Event = factor(sample(0:1,100,replace=TRUE),0:1,c('no event', 'death'))
)
fit <- cuminc(df$Time, df$Event, group = df$genotype)
ggcompetingrisks(fit)
p <- ggcompetingrisks(fit, multiple_panels = FALSE)
p + scale_linetype_manual(name="genotype",values=1:3,labels=c("A","B","C"))+
guides(col="none")
Please do dput(df) and paste the output as part of your question if the df I have above is different from yours. This way others can help as well.
If you need thicker lines, do:
old_geom <- ggplot2:::check_subclass("line", "Geom")$default_aes
update_geom_defaults("line", list(size = 1.5))
p + scale_linetype_manual(name="genotype",values=1:3,labels=c("A","B","C"))+
guides(col="none")
update_geom_defaults("line", list(size = old_geom$size))

R, how to change size of numbers in colorfulVennPlot?

I need to increase the size of the numbers in a Venn diagram created with colorfulVennPlot as in example below. Any help is greatly appreciated.
library(colorfulVennPlot)
y <- c(37,29,6,232,121,77,25)
names(y) <- c("001","010","011","100","101","110","111")
labels <- c("A","B","C")
plot.new()
plotVenn3d(y, labels, Colors=rainbow(7), Title = "This is an example of a 3D Venn plot")
The labels and title can be adjusted with the shrink parameter. But I don't see a way to change the numbers inside the Venn diagram in the current version of plotVenn3d. There might be an easier workaround, but one option is to create a tweaked version of the plotVenn3d function with a new parameter added for adjusting the size of the numbers.
To get the function code, just type plotVenn3d in the console. Copy the code to a new R script file and give the function a new name, say, myVenn. Now, go to the last line of the function and change it from this:
for (i in 1:7) grid.text(values[i], centerLocations[i, 1],
centerLocations[i, 2])
to this:
for (i in 1:7) grid.text(values[i], centerLocations[i, 1],
centerLocations[i, 2], gp=gpar(fontsize=num.size))
Notice how we added a new argument num.size that sets the font size for the numbers inside the Venn diagram. Now go back to the top where we declare the function arguments, and change it from this:
myVenn = function (x, labels = c("A", "B", "C"),
Colors = c("red", "yellow", "orange", "lightblue", "purple",
"green", "grey"),
Title = NULL, shrink = 1, rot = 0)
to this (in order to add the num.size argument to the function declaration):
myVenn = function (x, labels = c("A", "B", "C"),
Colors = c("red", "yellow", "orange", "lightblue", "purple",
"green", "grey"),
Title = NULL, shrink = 1, rot = 0, num.size=20)
Run the code for the new function to load the function into the global environment. Now you can use myVenn to plot your data and play with the value of num.size until you get something you like.
For example:
myVenn(y, labels, Colors=rainbow(7), Title = "This is an example of a 3D Venn plot",
num.size=50)

Legend appears, but it does not show color

I am using R for plotting. When my graph plots the legend appears where I want it to be but the colors are missing. mtcars 2 is a modified version of mtcars (one of the pre-loaded data sets) that adds a model and country of origin to the data set. mtcars.pca is what I named my redundance analysis (rda function under vegan), and mtcars.clust is titled for hierarchical clustering of the continuous factors of mtcars (hclust function of vegan) Below is the code I am using with mtcars2.
pca.fig = ordiplot(mtcars.pca, type = "none", las=1, xlim=c(-15,15), ylim = c(-20,10))
points(pca.fig, "sites", pch = 19, col = "green", select = mtcars2$origin =="domestic")
points(pca.fig, "sites", pch = 19, col = "blue", select = mtcars2$origin =="foreign")
ordiellipse(mtcars.pca, mtcars2$origin, conf = 0.95, label = FALSE)
ordicluster(mtcars.pca, mtcars.clust, col = "gray")
legend("bottomright", title="Car Origin", c("domestic", "foreign"), col = "origin")
You need to specify a vector of colours in legend and also a pch:
library("vegan")
data(dune, dune.env)
ord <- rda(dune)
plot(ord, type = "n")
cols <- c("red","blue","green")
points(ord, col = cols[dune.env$Use], pch = 19)
legend("bottomright", legend = levels(dune.env$Use), bty = "n",
col = cols, pch = 19)
If you don't add pch but just use col = cols legend() doesn't display any points. Because you used pch = 19 in your points() calls, use the same in the legend() call.
Also, note how to plot points of different colours in a single pass. I have some examples and explanation that go through the indexing trick I used in my code above to achieve this in a blog post of mine from a few years ago: http://www.fromthebottomoftheheap.net/2012/04/11/customising-vegans-ordination-plots/
I came to this question having the next problem in xts object:
I wanted to plot all time-series in xts object with legend. Moreover, there were around 20.
I used (wrong):
plot(returns_xts)
addLegend(...)
Correct version:
plot(returns_xts, legend.loc = "bottomright", col=1:20, lty = 1)
There is legend.loc parameter
col = 1:20 generates colors for you
Result:

How to add stripchart on a boxplot without outliers?

I made a boxplot without outliers.
boxplot(data, names = names(files), las = 2, outline=FALSE)
Now, I am trying to add stripchart on it:
stripchart(data, method = "jitter", add = T, col = "red")
Plot looks something like this:
I understand the reason why plot is like this: because I have not plotted outliers with boxplot. How to add stripchart properly (without outliers)?
I have solved my problem.
b <- boxplot(data, names = names(files), las = 2, outline=FALSE)
stripchart(data[!data %in% b$out], method = "jitter", add = T, col = "red",
vertical = T)

R legend issue, symbols of points are masked by lines

Is there a way to draw the lines in such a way that they would start on the side of the points, or allow the symbols to be in foreground?
My solution was to make the symbols bigger and more visible.
Edit 1: it's for plot {graphics} of the R program.
Edit 2: the code per popular request.
legend(2,.4,bty='n', c('sugar','citrus','none'), pch=c('s','c','u'), pt.bg='white',lty= c(1,2,3), lwd=1.5, title="Condition",pt.cex=c(1.5),cex=1.5)
Edit 3: This is solved for plot(type='b') but somehow not for legend.
Thanks for reading!
The only thing I can come up with is to manually finagle the dash lengths until they end up looking the way you want them. For instance, this:
> plot(1,1)
> legend(c("A", "B"), col = 1:2, x = 1, y = .8, lty="99", pch=1:2)
produces the image below.
The lty parameter allows you to specify the lengths of lines and dashes as hex characters. In this case, it's saying to create a line of length 9 then create a space of length 9 then repeat. It looks like 9 is about the best fit to space around a normal pch symbol.
Note that you'd probably need to adjust this depending on the size of the image, symbol, etc. My advice ultimately would be to export the image from R and touch up the image to meet your needs in graphic editing software.
Going with the suggestion by #JeffAllen, here is a way to get what I think you might want. It requires modifying the legend() function to return the position of the points (these are given by x1 and y1 in body(legend)[[46]]).
legend2 <- legend
body(legend2)[[49]] <- quote(
invisible(list(rect = list(w = w, h = h, left = left, top = top),
text = list(x = xt, y = yt), points = list(x = x1, y = y1)))
)
Make a plot:
plot(-100:100, -100:100, type = "b")
While drawing the legend, draw white circles (pch = 21 with pt.bg = 'white') over the lines, and assign the values invisibly returned by legend2() to an object. Note also the changes to pt.lwd and pt.cex.
myLegend <- legend2(1, .8, bty = 'n', c('sugar','citrus','none'), pch = 21,
pt.bg = 'white', pt.lwd = 0, lty = c(1, 2, 3), lwd = 1.5, title = "Condition",
pt.cex = c(1.8), cex = 1.5)
Finally, draw the characters you'd like to use in the legend using points(), supplying the x and y values from the object myLegend.
points(myLegend$points$x, myLegend$points$y, pch = c('s','c','u'), cex = 1.5)
And this should get you something like:
You could also use the filled points offered by R (pch=21:25) and specify the fill color using pc.bg which gets passed to the points call when creating a legend.
plot(1,1)
legend(c("A", "B"), col = 1:2, x = 1, y = .8, lty=1, pt.bg=1:2, pch=21:22)
generates the following:

Resources