Display legends on a combined ggplot2 plot - Stacked bar and line - r

I have a ggplot, which is a combination of a stacked graph and line graph
ggplot() +
geom_bar(data=smr2, aes(x=Pract, y=value, fill=variable), stat='identity') +
theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5)) +
geom_line(data=summarised[,1:3], aes(x=Pract,y=YTDTarget, group=1),size = 1) +
geom_point(data=summarised[,1:3], mapping = aes(x = Pract, y = YTDTarget),size=2.5)+
geom_text_repel(data=summarised[,1:3], aes(x=Pract,y=YTDTarget,label=YTDTarget), size = 5)
I want to add the legend for line graph. But the part group=1 seems to prevent this.
The graph I created is as
Also, please help to change the name of the legend from variable to "Actuals"
This graph is for compare the Target(line graph) against actually achieved(stacked Bar).

Please try this:
To geom_line add dummy variable (to add it to legend - in this case I'm using linetype).
geom_line(data = summarised[,1:3],
aes(Pract, YTDTarget, group = 1, linetype = ""),
size = 1)
To change legend name add labs() to your plot.
labs(fill = "Actuals",
linetype = "My Line Name")

Related

ggplot2 unable to color legend icons

I'm trying to use ggplot2 to make some sort of timeline using values from a dataframe (df). I've managed to plot the data exactly how I want it (the different colored line segments connecting the x-marks in this exact order, i.e., from left to right: 'early', 'unknown', 'late', 'sub'). The startpoint and endpoint columns in the dataframe are used to define the positions of the points and line segments.
The problem is that the legend doesn't show the color of the 'x' icons, they are just grey. I've tried adding scale_color_manual() and scale_fill_manual() commands but they don't seem to change anything. The legend does display the correct color when I change the shape to shape = 21, however, I really want the shape to be 4 (x icons). I don't care about the shape of the legend though but scale_shape_manual() again didn't change anything about the legend.
I have also tried placing different color arguments inside and outside the aes() argument of ggplot(), geom_segment() and/or geom_point().
How can I make the icons from the legend show the correct color?
Below I added a piece of code to reproduce the problem.
library(ggplot2)
library(RColorBrewer)
## Define dataframe
df <- data.frame(Var = c("sub","late","unknown","early"),
Time = c(10,267,0,1256),
Endpoint = c(1533,1523,1256,1256),
Startpoint = c(1523,1256,1256,0))
colorscheme <- RColorBrewer::brewer.pal(9, "Set1")[c(1,4,2,3)]
## Make plot
ggplot(df, aes(x="", y=Endpoint, fill=Var), color =colorscheme) +
geom_segment( aes(x="", xend="", y=Startpoint, yend=Endpoint), color = colorscheme) +
geom_point(aes(x="", y=Endpoint),size=5, shape=4 , color = colorscheme) +
coord_flip()
Thanks in advance for any suggestions!
You should use color instead of fill. To remove the line from the legend, use guides(color = guide_legend(override.aes = list(linetype = 0))) or use show.legend = F in geom_segment.
Also, arguments passed in ggplot need not to be repeated afterward.
ggplot(df, aes(x="", y=Endpoint, color=Var), colorscheme) +
geom_segment(aes(xend="", y=Startpoint, yend=Endpoint)) +
geom_point(size=5, shape=4) +
coord_flip() +
guides(color = guide_legend(override.aes = list(linetype = 0)))
#or
ggplot(df, aes(x="", y=Endpoint, color=Var), colorscheme) +
geom_segment(aes(xend="", y=Startpoint, yend=Endpoint)) +
geom_point(size=5, shape=4) +
coord_flip()
Try this:
ggplot(df, aes(x = "", y = Endpoint, color = Var), colorscheme) +
geom_segment(aes(x = "", xend = "", y = Startpoint, yend = Endpoint), show.legend = FALSE) +
geom_point(aes(x = "", y = Endpoint), size = 5, shape = 4) +
coord_flip()
In this way legend will show only X

Duplicate legends in overlayed density plots using ggplot2

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)

Plot three-variable line chart

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)

Custom legend in ggplot2: how to fill without factors?

I am making a personality survey that will generate score reports for participants. I want to make these as easy to read and understand as possible, so I am generating a normal curve for the surveyed trait and a line showing the person where they fall on the curve.
First, let's generate some data:
sample <- as.data.frame(rnorm(1000, 0, 1))
names(sample) <- "trait"
score <- mean(sample$trait)
My problem is with the legend—I cannot figure out how to customize the legend to display 1) a filled "population" color when I'm not graphing multiple factors, and 2) the line showing the participant's score.
I can get close:
ggplot(sample, aes(x=trait)) +
geom_density(fill="blue") +
geom_density(aes(fill="Population")) +
geom_vline(aes(xintercept=score, color="You")) +
geom_vline(xintercept=score, color='red',
linetype="solid",size=1.5) +
scale_colour_manual(values=c('Population'='blue',
'You'='red'))
Graph image 1
But this does not use the colors specified, and has extraneous "colour" and "fill" text in the legend.
If I change the geom_density aesthetic to color instead of fill and leave everything else the same...
geom_density(aes(color="Population")) +
...This correctly applies the colors, but then does not fill the "Population" box in the legend with blue.
Graph image 2
Optimally, I'd like to fill the "Population" box blue and remove the red box around the "You" line in the legend. How can I achieve this?
I hope this can be used.
ggplot(sample, aes(trait)) +
geom_density(aes(fill = "Population")) +
geom_vline(aes(xintercept = mean(trait), color = "You")) +
theme(legend.title = element_blank()) +
scale_color_manual(values = "red", breaks = "You") +
scale_fill_manual(values = "blue", breaks = "Population")

ggplot: Manually add legends for aesthetics that are not mapped

I want to produce a barplot overlayed with dots where both have separate legends. Also, I want to choose the color of the bars and the size of the dots using the arguments outside aes(). As both are not mapped, no legend is produced.
1) How can I add a legend manually for both fill and size?
library(ggplot2)
d <- data.frame(group = 1:3,
prop = 1:3 )
ggplot(d, aes(x=group, y=prop)) +
geom_bar(stat="identity", fill="red") +
geom_point(size=5)
This is what I came up with: I used dummy mappings and modified the legend according to my needs afterwards. But this approach appears clumsy to me.
2) Is there a manual way to say: Add a legend with this title, these shapes, these colors etc.?
d <- data.frame(dummy1="d1",
dummy2="d2",
group = 1:3,
prop = 1:3 )
ggplot(d, aes(x=group, y=prop, fill=dummy1, size=dummy2)) +
geom_bar(stat="identity", fill="red") +
geom_point(size=5) +
scale_fill_discrete(name="fill legend", label="fill label") +
scale_size_discrete(name="size legend", label="size label")
Above I mapped fill to dummy1. So I would expect scale_fill_discrete to alter this legend. But it appears to modify the size legend instead.
3) I am not sure what went wrong here. Any ideas?
I'm not sure why you say "Also, I want to choose the color of the bars and the size of the dots using the arguments outside aes()". Is it something you're trying to do or is it something that you have to do given how ggplot works?
If it's the latter, one solution is as under -
library(ggplot2)
d <- data.frame(group = 1:3,
prop = 1:3 )
ggplot(d, aes(x=group, y=prop)) +
geom_bar(stat="identity",aes( fill="label")) +
geom_point(aes(size='labelsize')) +
scale_fill_manual(breaks = 'label', values = 'red')+
scale_size_manual(breaks = 'labelsize', values = 5)

Resources