adding legend to plot with 2 geom points - r

I have this plot
dat = data.frame(group = rep("A",3),subgroup= c("B","C","D"), value= c(4,5,6),avg = c(4.5,4.5,4.5))
ggplot(dat, aes(x= group, y =value, color = fct_rev(subgroup) ))+
geom_point()+
geom_point(data = dat ,aes(x = group, y = avg), color = "blue",pch = 17, inherit.aes = FALSE)
I need to show 2 legends: 1 for the fct_rev(subgroup) which I already there but there is no legend for "avg".
How can i add a legend that is a blue triangle pch 17 with the title "avg?
thank you

Maybe like this?
ggplot(dat, aes(x= group, y =value, color = fct_rev(subgroup) ))+
geom_point()+
geom_point(data = dat ,aes(x = group, y = avg,shape = "Mean"),
color = "blue", inherit.aes = FALSE) +
scale_shape_manual(values = c('Mean' = 17))

Using data from original post.
Legends do not work like that in ggplot. Why not add a geom_text at the average? I see that you have a column with the average being repeated. This seems like a bad way to handle the data, but irrelevant right now.
My proposed solution:
ggplot(dat)+
geom_point(aes(x= group, y =value, color = subgroup))+
geom_point(aes(x = group, y = avg), color = "blue",pch = 17, inherit.aes = FALSE) +
geom_text(aes(x=1, y = 4.5), label = "avg", nudge_x = .1)
You could also add a hline to symbolize the average, which would aesthetically look nicer.

Related

How to create an legend for ggplot for just one series of data and then add legend for additional horizontal lines?

I'm wanting to prepare a simple plot with some points and horizontal lines with a legend. The code below generates the desired plot and a legend but the legend symbols are combinations of the shape and line, when I would just like a shape for the shape and a line for the line.
dat <- iris %>% select(Sepal.Length)
dat$Type <- "Sepal.Length"
ggplot() +
geom_point(data = dat, aes(x = as.numeric(row.names(dat)), y = Sepal.Length, colour = Type), shape = 10, size = 2) +
geom_hline(aes(yintercept = 6, colour = "Some line"), linetype = "dashed")
Custom linetypes and shapes are assigned using scale_*_manual, like so:
dat %>%
ggplot() +
geom_point(aes(x = as.numeric(row.names(dat)), y = Sepal.Length, shape = Type), size = 2) +
geom_hline(aes(yintercept = 6, linetype = 'Some line')) +
scale_linetype_manual(values = c('Some line' = 'dashed')) +
scale_shape_manual(values = c('Sepal.Length' = 10))

ggplot2 fill legend does not display the correct "fill" color

I am confused of this problem for a long time. A simple data frame is constructed as follows
data <- data.frame(
x = 1:5,
y = 5:1,
fill = c(rep("pink", 3), rep("blue", 2)),
shape = c(rep(21, 3), rep(22, 2))
)
Suppose I wand to show the legend of the fill
uniFill <- unique(data$fill)
p <- ggplot(data,
mapping = aes(x = x,
y = y,
fill = fill)) +
geom_point(shape = data$shape) +
# show legend so that I do not call `scale_fill_identity()`
scale_fill_manual(values = uniFill,
labels = uniFill,
breaks = uniFill)
p
The graphics are OK, however, the legend is not correct
I guess, maybe different shapes (21 to 25) cannot be merged? Then, I partition the data into two subsets where the first set has shape 21 and the second has shape 22.
data1 <- data[1:3, ]
data2 <- data[4:5, ]
# > data1$shape
# [1] 21 21 21
# > data2$shape
# [1] 22 22
ggplot(mapping = aes(x = x,
y = y,
fill = fill)) +
geom_point(data = data1, shape = data1$shape) +
geom_point(data = data2, shape = data2$shape) +
scale_fill_manual(values = uniFill,
labels = uniFill,
breaks = uniFill)
Unfortunately, the legend does not change. Then, I changed the shape from a vector to a scalar, as in
ggplot(mapping = aes(x = x,
y = y,
fill = fill)) +
geom_point(data = data1, shape = 21) +
geom_point(data = data2, shape = 22) +
scale_fill_manual(values = uniFill,
labels = uniFill,
breaks = uniFill)
The legend of the fill color is correct finally...
So what happens here? Is it a bug? Is it possible to just add a single layer but with different shapes (21 to 25)?
A possible solution is that one can add component guides(), as in
p +
guides(fill = guide_legend(override.aes = list(fill = uniFill,
shape = 21)))
But I am more interested in why p does not work (legend)
The main reason your legend is not working in your first example is because you did not put your shape in the aesthetics.
I have a couple other suggestions: Do not define colors in your data frame; instead define a column to change the aesthetics using a code. Then define your fill and shape values explicitly. Each of the scales needs to have the same name - in this case "Legend."
Give this edit a try.
data <- data.frame(
x = 1:5,
y = 5:1,
fill = c(rep("p", 3), rep("b", 2))
)
uniFill <- c("p"="pink", "b"="blue")
uniShape <- c("p" = 21, "b" = 22)
p <- ggplot(data,
mapping = aes(x = x,
y = y,
fill = fill,
shape = fill)) +
geom_point() +
# show legend so that I do not call `scale_fill_identity()`
scale_fill_manual("Legend",values = uniFill,
labels = uniFill)+
scale_shape_manual("Legend",values = uniShape,
labels = uniFill)
p
(edit) If your fill and shape aesthetics do not match up, I don't see any other way than to use guides and two legends. Notice that if your attribute column is descriptive, you do not need to set the labels and your code will be cleaner (see shape vs fill aesthetics).
data <- data.frame(
x = 1:5,
y = 5:1,
fill = c(rep("p", 3), rep("b", 2)),
shape = c(rep("circles", 2), rep("squares", 3))
)
uniFill <- c("p"="pink", "b"="blue")
uniShape <- c("circles" = 21, "squares" = 22)
p <- ggplot(data,
mapping = aes(x = x,
y = y,
fill = fill,
shape = shape)) +
geom_point() +
# show legend so that I do not call `scale_fill_identity()`
scale_fill_manual("Legend fill",values = uniFill,
labels = uniFill)+
scale_shape_manual("Legend shape",values = uniShape )+
guides(fill = guide_legend("Legend fill", override.aes = list(shape = 21)))
p

Need to add legend and fix axis in ggplot [duplicate]

This question already has answers here:
Add legend to ggplot2 line plot
(4 answers)
Closed 2 years ago.
I'm new to ggplot and I'm trying to figure out how to add a legend to a graph and re-label the x-axis. I've enclosed the plotting code and resulting graph . I would like to add a legend that explains what the blue line and the green and red dots are. I would also like the years on the x-axis to appear as 2018, 2019, ... , 2020 instead of 2017.5, 2010.0, ..., 2020.0. I can't find a solution in the online documentation. Thanks for your help.
ggplot(data = annual_rate_preds) +
geom_point(mapping = aes(x = year, y = predicted), color = 'green') +
geom_line(mapping = aes(x = year, y = observed), color = 'blue') +
geom_point(data = backfit_rate_preds, mapping = aes(x = target_year, y = rate_pred),
shape = 18, color = 'red', size = 2) +
theme(plot.title = element_text(size = 10))
Using some random example data this could be achieved like so:
Using scale_x_continuous(breaks = scales::pretty_breaks()) gives pretty x-axis breaks and labels
To get a legend you have to map on aesthetics, i.e. move color inside aes(). The color values can then be set via scale_color_manual
Labels for the axes, legend, ... can be set via labs()
Most tricky part is to get the legend right. To this end I make use of guides and guide_legend to adjust the legend such that for observed only a solid line is shown while for the other categories only points (shape 16) show up.
library(ggplot2)
set.seed(42)
annual_rate_preds <- data.frame(
predicted = runif(13, -.1, .1),
observed = runif(13, -.1, .1),
year = 2008:2020
)
backfit_rate_preds<- data.frame(
rate_pred = runif(13, -.1, .1),
target_year = 2008:2020
)
ggplot(data = annual_rate_preds) +
geom_point(mapping = aes(x = year, y = predicted, color = 'predicted')) +
geom_line(mapping = aes(x = year, y = observed, color = 'observed')) +
geom_point(data = backfit_rate_preds, mapping = aes(x = target_year, y = rate_pred, color = 'rate_pred'),
shape = 18, size = 2) +
scale_x_continuous(breaks = scales::pretty_breaks()) +
scale_color_manual(values = c(predicted = "green", observed = "blue", rate_pred = "red")) +
theme(plot.title = element_text(size = 10)) +
guides(color = guide_legend(override.aes = list(linetype = c("solid", "blank", "blank"), shape = c(NA, 16, 16)))) +
labs(x = "Year", y = NULL, color = NULL)

added vline does not appear on plot

I have this plot
dat = data.frame(x = c(55,56) , y = c(200,300))
ggplot(dat, aes(x = factor(x, ordered = TRUE), y =y)) +
geom_bar(stat = "identity")+
geom_vline(aes(xintercept = 55, linetype = "solid" ), color = "red")
The vertical line is not appearing. How can I make it appear over the bars? Thank you.

Legend units for geom_point size

I have used geom_point in ggplot2 to display values as the area of each point:
geom_point(aes(size = sqrt(z/pi))
However, the legend units are the transformed values, is it possible to have the legend display the original values alongside their respective bubble size?
Edit: sorry I should have provided more information to begin with
library(ggplot2)
data <- data.frame(x = sample(1:10), y = sample(1:10), z = sample(1:10), colour = c("red", "yellow", "green","pink","black","brown","grey","white","purple","beige"))
ggplot(data, aes(x = x, y = y)) + geom_point(aes(size = sqrt(z/pi)), pch = 21) + aes(fill = colour) + scale_fill_brewer(palette = "set1")
Try adding:
+scale_colour_manual(guide = guide_legend(override.aes=aes(size=values)))

Resources