I am trying to generate density plot with two overlaid distributions using ggplot2. My data looks like:
diag_elements <- data.frame(x = c(diag(Am.dent), diag(Am.flint)),
group=rep(c("Dent", "Flint"), c(length(diag(Am.dent)), length(diag(Am.flint)))))
And my call to ggplot is:
ggplot(diag_elements) +
geom_density(aes(x=x, colour=group, fill=group), alpha=0.5) +
labs(x = "Diagonal elements of the matrix", y = "Density", fill = "Heterotic Group") +
theme(legend.position = c(0.85, .75))
However, instead of simply renaming the legend with the more complete name specified in fill, this generates a second legend:
Does anyone have any suggestions for getting this same graph, but without the improperly formatted legend?
Thanks!
The other option is guides which allows specific removal of certain legneds. You simply add to your ggplot
+guides(color=FALSE)
Related
I have a two small sets of points, viz. (1,a1),...,(9,a9) and (1,b1),...,(9,b9). I'm trying to interpolate these two set of points separately by using splines with the help of ggplot2. So, what I want is 2 different splines curves interpolating the two sets of points on the same plot (Refer to the end of this post).
Since I have a very little plotting experience using ggplot2, I copied a code snippet from this answer by Richard Telford. At first, I stored my Y-values for set of points in two numeric variables A and B, and wrote the following code :
library(ggplot2)
library(plyr)
A <- c(a1,...,a9)
B <- c(b1,...,b9)
d <- data.frame(x=1:9,y=A)
d2 <- data.frame(x=1:9,y=B)
dd <- rbind(cbind(d, case = "d"), cbind(d2, case = "d2"))
ddsmooth <- plyr::ddply(dd, .(case), function(k) as.data.frame(spline(k)))
ggplot(dd,aes(x, y, group = case)) + geom_point() + geom_line(aes(x, y, group = case), data = ddsmooth)
This produces the following output :
Now, I'm seeking for an almost identical plot with the following customizations :
The two spline curves should have different colours
The line width should be user's choice (Like we do in plot function)
A legend (Specifying the colour and the corresponding attribute)
Markings on the X-axis should be 1,2,3,...,9
Hoping for a detailed solution to my problem, though any kind of help is appreciated. Thanks in advance for your time and help.
You have already shaped your data correctly for the plot. It's just a case of associating the case variable with colour and size scales.
Note the following:
I have inferred the values of A and B from your plot
Since the lines are opaque, we plot them first so that the points are still visible
I have included size and colour parameters to the aes call in geom_line
I have selected the colours by passing them as a character vector to scale_colour_manual
I have also selected the sizes of the lines by calling scale_size_manual
I have set the x axis breaks by adding a call to scale_x_continuous
The legend has been added automatically according to the scales used.
ggplot(dd, aes(x, y)) +
geom_line(aes(colour = case, size = case, linetype = case), data = ddsmooth) +
geom_point(colour = "black") +
scale_colour_manual(values = c("red4", "forestgreen"), name = "Legend") +
scale_size_manual(values = c(0.8, 1.5), name = "Legend") +
scale_linetype_manual(values = 1:2, name = "Legend") +
scale_x_continuous(breaks = 1:9)
Created on 2020-07-15 by the reprex package (v0.3.0)
I need to plot a line chart that contains 2 lines, as per the dataset below:
I need each line of the chart to match the Technique. The values of X and Y are Release and Added respectively. The graph I need to generate is similar to the one in the figure below:
To plot the first line, I tried:
plot(IrisChangeModules[IrisChangeModules$Technique=="aop"]$Added, IrisChangeModules[IrisChangeModules$Technique=="aop"]$Release, type = "l")
Using ggplot (not a base r solution though), one way of getting your desired output can be:
library(ggplot2)
ggplot(dataset, aes(x=Release, y=Added, group=Technique)) + geom_line(aes(linetype = Technique, color=Technique)) + geom_point(aes(color = Technique)) + theme_bw()
The output given your dummy data looks:
You can play with the different parameters of ggplot to position the legend and other aspects of the plot.
UPDATE:
Remove ylab("Added Modules") + scale_color_discrete(name = "SPL Techniques") from your script and save the output on a variable as follows:
x <- ggplot(IrisChangeModules, aes(x=Release, y=Added, group=Technique)) + geom_line(aes(linetype = Technique, color=Technique)) + geom_point(aes(color = Technique)) + theme_bw()
Then overlay your modified label and new legend title as:
x+ labs(y = "Added Modules") + scale_fill_discrete(name = "SPL Techniques")
That'll give you what you want.
Firstly create an ordered release int
IrisChangeModules$release_n = 1:nrow(IrisChangeModules)
Now create a blank plot, type="n" means nothing is actually plotted.
plot(Added~release_n,data=IrisChangeModules,type="n",xaxt = "n")
Create axis labels with the original variable ( you may need to update the at if you have more than 4 releases).
axis(1,at=1:4,labels=IrisChangeModules$Release)
Add lines are required
lines(Added~release_n,data=IrisChangeModules[IrisChangeModules$tech=="dop",],type='l',col="green")
lines(Added~release_n,data=IrisChangeModules[IrisChangeModules$tech=="aop",],type='l',col="red")
Add a legend, make sure you are updating if you add more lines
legend(1,90,
legend=c("dop", "aop"),
col=c("green", "red"),
lty=1,
cex=0.8)
I am analyzing the ecological data atm, so I do like to draft a CCA plot that contains information about sites, spp, and environmental variables data. And also coloring geom_text related to the sites and spp separately? Is there any codes enables me to do so in the ggplot2?
I had tried to add two geom_text(spp and sites variables) in the single phrase of codes, but it does not work out as I expected since the geom_text from these two variables are overlapping each other. And then I did try to add colors to geom_text separately, but it does not work out as well. I tried to plot the graph using the auto_plot function of ggvegan, I like the graph the way it orientates the colors and word size of the graph, but the texts were overlapping.
ggplot() +
geom_point(aes(x=CCA1, y=CCA2), data=filter(vare_tbl, ccatype=="species"))+ geom_text_repel(aes(x=CCA1, y=CCA2, label=vgntxt, size=3.5),
data=vare_tbl, seed=123) +
geom_text_repel(aes(x=CCA1, y=CCA2, label=vgntxt, size=3.5),
data=vare_sam_tbl, seed=123)+
geom_segment(aes(x=0, y=0, xend=CCA1, yend=CCA2), arrow=arrow(length = unit(0.2,"cm")),
data=filter(vare_tbl, ccatype=="bp"), color="blue") +
coord_fixed() +
scale_colour_manual(values = c("blue", "black"))+ #this code isn't working
theme_classic() +
theme(legend.position="none")
##Autoplot function of ggvegan
autoplot(cca2, arrows = TRUE, geom = "text", legend = "none")
I obtained the codes to plot the biplot graph from https://blogs.ncl.ac.uk/mep/2018/04/08/reproducible-publication-quality-multivariate-plots-in-r/.
And I obtained the codes to color up the geom_text from https://ggplot2.tidyverse.org/reference/geom_point.html, by doing so the factor(cyl) wasn't work out for me.
I want to create a single legend for a bubble chart with positive and negative values like in plot below, generated using sp::bubble().
But, for various reasons I want to duplicate this in ggplot2. The closest I have gotten is to generate a single legend with scaled symbols, but the actual bubbles themselves are'nt scaled.
The above plot was created using the code below
# create data frame
x=sample(seq(1,50),50,T)
y=sample(seq(1,50),50,T)
plot_dat=data.frame(x=x,y=y,value=rnorm(50,0,25))
# plot
library(ggplot2)
ggplot(data=plot_dat, aes(x=x, y=y,colour=factor(sign(value)), size=value)) +
geom_point() +
scale_size(breaks = c(-40,-30,-20,-10,0,10,20,30,40,50), range = c(0.5,4)) +
scale_colour_manual(values = c("orange", "blue"), guide=F) +
guides(size = guide_legend(override.aes = list(colour = list("orange","orange","orange","orange","blue","blue","blue","blue","blue","blue"),size=c(3,2.5,2,1,0.5,1,2,2.5,3,4))))
Continue using abs(value) for size and sign(value) for color.
Provide the breaks= argument of scale_size_continuous() with duplicates of breaks required (e.g. c(10,10,20,20,...)). Next, provide labels= with the values you desire. Finally, use guides() and override.aes to set your own order of values and colours.
ggplot(data=plot_dat, aes(x=x, y=y,colour=factor(sign(value)), size=abs(value))) +
geom_point() +
scale_color_manual(values=c("orange","blue"),guide=FALSE)+
scale_size_continuous(breaks=c(10,10,20,20,30,30,40,40,50,50),labels=c(-50,-40,-30,-20,-10,10,20,30,40,50),range = c(1,5))+
guides(size = guide_legend(override.aes = list(colour = list("orange","orange","orange","orange","orange","blue","blue","blue","blue","blue"),
size=c(4.92,4.14,3.50,2.56,1.78,1.78,2.56,3.50,4.14,4.92))))
To assign exact values for the size= argument in the guides() function you could use function rescale() from the scales library. Rescale the entire range of values you are plotting, along with the break points provided to range= argument in scale_size_continuous().
set.seed(1234)
x=sample(seq(1,50),50,T)
y=sample(seq(1,50),50,T)
plot_dat=data.frame(x=x,y=y,value=rnorm(50,0,20))
library(scales)
rescale(c(abs(plot_dat$value),10,20,30,40,50),to=c(1,5))[51:55]
[1] 1.775906 2.562657 3.349409 4.136161 4.922912
I have some code that is plots a histogram of some values, along with a few horizontal lines to represent reference points to compare against. However, ggplot is not generating a legend for the lines.
library(ggplot2)
library(dplyr)
## Siumlate an equal mix of uniform and non-uniform observations on [0,1]
x <- data.frame(PValue=c(runif(500), rbeta(500, 0.25, 1)))
y <- c(Uniform=1, NullFraction=0.5) %>% data.frame(Line=names(.) %>% factor(levels=unique(.)), Intercept=.)
ggplot(x) +
aes(x=PValue, y=..density..) + geom_histogram(binwidth=0.02) +
geom_hline(aes(yintercept=Intercept, group=Line, color=Line, linetype=Line),
data=y, alpha=0.5)
I even tried reducing the problem to just plotting the lines:
ggplot(y) +
geom_hline(aes(yintercept=Intercept, color=Line)) + xlim(0,1)
and I still don't get a legend. Can anyone explain why my code isn't producing plots with legends?
By default show_guide = FALSE for geom_hline. If you turn this on then the legend will appear. Also, alpha needs to be inside of aes otherwise the colours of the lines will not be plotted properly (on the legend). The code looks like this:
ggplot(x) +
aes(x=PValue, y=..density..) + geom_histogram(binwidth=0.02) +
geom_hline(aes(yintercept=Intercept, colour=Line, linetype=Line, alpha=0.5),
data=y, show_guide=TRUE)
And output: