Adding manual legend in ggplot - r

I've looked through prior similar questions and (I think) have done everything that's been recommended in them. Still not getting the output I want.
I have a bunch of distributions, which I'm displaying in facetted graphs. I then draw vertical lines through them, which represent different interventions.
I'm trying to display a legend that contains both the fill color of the distributions as well as the line color of those extra lines. As far as I can tell, I'm doing everything right (setting the color command within aes(), using scale_colour_manual() to define the legend, etc). I'm still only getting the legend for the fill colors.
Here's my code:
ggplot(modCosts, aes(x=cost)) + geom_density(aes(fill=group)) + theme_bw() +
facet_wrap(~ country, scales="free") + scale_x_continuous(label = dollar) +
scale_fill_brewer(palette = "RdGy", name = "Income group", labels = c("HIC" = "High income", "UMIC" = "Upper-middle income", "LIC" = "Low income")) +
labs(y = "Density", x = "Cost", title = "Medical costs of surgery\nActual vs. modeled") +
geom_vline(data = surgCosts, aes(xintercept = CS.tert.lo, color = "red4")) +
geom_vline(data = surgCosts, aes(xintercept = CS.tert.hi, color = "red4")) +
geom_vline(data = surgCosts, aes(xintercept = CS.prim.lo, color = "red4"), lty = "dashed") +
geom_vline(data = surgCosts, aes(xintercept = CS.prim.hi, color = "red4"), lty = "dashed") +
geom_vline(data = surgCosts, aes(xintercept = Lap.tert.lo, color = "deepskyblue")) +
geom_vline(data = surgCosts, aes(xintercept = Lap.tert.hi, color = "deepskyblue")) +
geom_vline(data = surgCosts, aes(xintercept = Lap.prim.lo, color = "deepskyblue"), lty = "dashed") +
geom_vline(data = surgCosts, aes(xintercept = Lap.prim.hi, color = "deepskyblue"), lty = "dashed") +
geom_vline(data = surgCosts, aes(xintercept = Fx.tert.lo, color = "yellowgreen")) +
geom_vline(data = surgCosts, aes(xintercept = Fx.tert.hi, color = "yellowgreen")) +
scale_color_manual(name = "Reported cost", values = c("red4" = "red4", "deepskyblue" = "deepskyblue", "yellowgreen" = "yellowgreen"),
labels = c("Int1", "Int2", "Int3")) +
theme(axis.ticks = element_blank(), axis.text.y = element_blank(), legend.position = "right")
And here's the output I'm getting:
Any help would be greatly appreciated!

There's a show_guide=... argument to geom_vline(...) (and _hline and _abline) which defaults to FALSE. Evidently the view was that most of the time you would not want the line colors to show up in a legend. Here's an example.
df <- mtcars
library(ggplot2)
ggp <- ggplot(df, aes(x=wt, y=mpg, fill=factor(cyl))) +
geom_point(shape=21, size=5)+
geom_vline(data=data.frame(x=3),aes(xintercept=x, color="red"), show_guide=TRUE)+
geom_vline(data=data.frame(x=4),aes(xintercept=x, color="green"), show_guide=TRUE)+
geom_vline(data=data.frame(x=5),aes(xintercept=x, color="blue"), show_guide=TRUE)
ggp +scale_color_manual("Line.Color", values=c(red="red",green="green",blue="blue"),
labels=paste0("Int",1:3))
BTW a better way to specify the scale if you insist on using color names is this:
ggp +scale_color_identity("Line.Color", labels=paste0("Int",1:3), guide="legend")
which produces the identical plot above.

Related

Error in ggplot() + geom_line(data = Data, aes(x = mannings, y = HR2, : invalid (NULL) left side of assignment

I don't know why i have the error message, it was working then it wasn't. keep getting an error saying there is a probelm with the left side of the assignment. however, everything i have tried online hasn't worked.
Data <- read.csv("R_2.csv",header=TRUE,)
library(ggplot2)
colors <- c("HECRAS low" = "blue", "FloodModeller low flow" = "red", "HECRAS high flow" = "blue", "FloodModeller high flow" = "red")
P1 = ggplot() +
geom_line(data = Data, aes(x = mannings, y = HR2, color = "HECRAS low"), linetype= "dotted", size=1) +
geom_line(data = Data, aes(x = n, y = FM2, color = "FloodModeller low flow"), linetype= "dotted", size=1) +
geom_line(data = Data, aes(x= Mannings, y= Hrhigh2, color = "HECRAS high flow"), size=1) +
geom_line(data = Data, aes(x= N, y= Fmhigh2, color = "FloodModeller high flow"), size=1) +
ggtitle("change in accuracy with resolution")+
labs(x= "resolution",
y= "accuracy (%)",
color= "Legend")+
scale_color_manual(values = colors)+
guides(color = guide_legend(override.aes = list(linetype = c( "solid", "dotted"))))+
theme(legend.key.size=unit(2, "lines"))+
theme_light()+
personal_theme = theme(plot.title =
element_text(hjust = 0.5))
print(P1 + personal_theme)

How to adjust both the line and point shape size in a legend to be different sizes?

I'm trying to adjust the point and line size independently in my legend. I'm wanting to be able to discern between the dashed and solid line while also having my point shapes be distinctive enough overtop of the line in the legend. Right now, I can't seem to figure out how to make the line smaller - I've figured out how to adjust the point size though. Any help/thoughts are all appreciated; definitely still a newbie. Thanks!
I'll post an image and code below:
Image of figure with points enhanced, but still can't get line to size correctly in the legend
- Chase
ggplot(df, aes(x = Psych.Distress.Sum, y = Likelihood.Max, color = Feedback)) +
geom_smooth(method = "lm", se = T, aes(linetype = Feedback)) +
geom_jitter(aes(shape = Feedback)) +
labs(x = "Psychological Distress", y = "Endorsement of Max's Feedback Strategy") +
apatheme +
theme(axis.title = element_text(face="bold")) +
theme(legend.text = element_text(face="bold")) +
theme(legend.position = c(0.87, 0.13)) +
scale_color_grey(end = .5) +
theme(legend.key.height= unit(.5, 'cm'),
legend.key.width= unit(1, 'cm')) +
guides(colour = guide_legend(override.aes = list(size= 3, linetype=0)))
This is tricky. Here's a hacky way using two plots that are overlaid on top of each other using patchwork. To prove that the data are aligned, I made the 2nd plot's text be semi-transparent red, but we could make it totally transparent with color #FF000000. This method is a little brittle, since the plots will come out of alignment if they have different ranges or different formats. But if we adjust for that, they line up perfectly with no extra fuss.
Your question didn't include any sample data so I used the mtcars data set.
library(patchwork)
library(ggplot2)
# This layer has the `geom_smooth` and black axis text
(a <- ggplot(mtcars, aes(x = wt, y = mpg, color = as.factor(am))) +
geom_smooth(method = "lm", se = T, aes(linetype = as.factor(am))) +
scale_color_grey(end = .5) +
guides(linetype = guide_legend(override.aes = list(size = 1.2))) +
labs(x = "Psychological Distress",
y = "Endorsement of Max's Feedback Strategy",
linetype = "Line legend", color = "Line legend") +
coord_cartesian(ylim = c(10, 35)) +
theme_classic() +
theme(axis.title = element_text(face="bold")) +
theme(legend.text = element_text(face="bold")) +
theme(legend.position = c(0.7, 0.8)))
# This layer has the `geom_jitter` and red semi-clear axis text
(b <- ggplot(mtcars, aes(x = wt, y = mpg, color = as.factor(am))) +
geom_jitter(aes(shape = as.factor(am))) +
scale_color_grey(end = .5) +
guides(shape = guide_legend(override.aes = list(size = 3))) +
coord_cartesian(ylim = c(10, 35)) +
labs(x = "", y = "",
color = "Point legend", shape = "Point legend") +
theme_classic() +
theme(plot.background = element_blank(),
panel.background = element_blank(),
axis.text = element_text(color = "#FF000055")) +
theme(legend.position = c(0.7, 0.55)))
a + inset_element(b, 0, 0, 1, 1, align_to = "full")

Customize lines in ggplot linegraph with multiple lines

I build this graph:
labels.minor <- c("nie","selten","manchmal", "mehrmals", "oft", "sehr oft", "immerzu")
df_ebf <- df_ebf %>%
map_df(rev)
ggplot(data=df_ebf, aes(x=forcats::fct_inorder(Skalen), y=Werte, group="")) +
geom_line(aes(y = Werte, color = "#003560")) +
geom_line(aes(y = SD_plus, color = "#8DAE10", linetype = "dashed")) +
geom_line(aes(y = SD_minus, color = "#8DAE10",linetype = "dashed")) +
geom_point(color = "#003560") +
coord_flip() +
labs(x="EBF-Skalen") +
scale_y_continuous(limits = c(0, 6), breaks = c(0,1,2,3,4,5,6), labels = paste0(0:6, "\n", labels.minor), sec.axis = sec_axis(~.x, breaks = 0:6)) +
scale_x_discrete(expand = c(0,0)) +
theme(panel.grid.major.y = element_blank(),panel.grid.minor.x = element_blank(),axis.line.x = element_line(size = 1, colour = "black", linetype=1),axis.title=element_blank())
But instead of changing the style of the lines, the styling just appears in the legend.
take them out of the aes:
aes(...), color="..", linetype=".."

How to add a second legend using different `geom_line`?

I am plotting the relationship between two variables (X and Y) for different individuals (IDs). This relationship is shown both with the real values (geom_point) and with lines which represent the prediction of the relationship between the variables for different individuals Linear Mixed Effect Models (LME). On top of that, the linear relationship between the two variables and for the different individuals is done using three levels of a second quantitative predictor (Z).
Thus, what I do is to use geom_point() for showing the relationship between raw values of X and Y. Then, I use three geom_line() for three LME with different levels of Z. Thus, each geom_line() draws the six lines for the six IDs for a fixed Z. So, since I have 3 Z levels and I have 3 geom_line(), I have 18 lines.
I tried this (note: code is simplified):
Plot_legend <- ggplot(df, aes(x=X, y=Y, colour=ID)) +
geom_point(size=1.5,alpha=0.2) +
geom_line(aes(y=predict(model,df.Z_low), group=ID, linetype = c("1")), size=1.5, alpha=0.6, color = line_colors[3]) +
geom_line(aes(y=predict(model,df.Z_medium), group=ID, linetype = c("2")), size=1.5, alpha=0.6, color = line_colors[2]) +
geom_line(aes(y=predict(model,df.Z_high), group=ID, linetype = c("3")), size=1.5, alpha=0.6, color = line_colors[1]) +
geom_abline(aes(slope=1,intercept=0),linetype="dashed",color="grey52",size=1.5) +
theme_bw() +
theme(legend.text=element_text(size=18),
legend.title = element_text(size=19, face = "bold",hjust = 0.5),
legend.key=element_blank(),
legend.background = element_rect(colour = 'black', fill = 'white', size = 1, linetype='solid')) +
guides(color=guide_legend(override.aes=list(fill=NA)))
However, as you can see, the legend for the three geom_line() is not what I desire. I would like to appear as title Z instead of c("10th"). Also, the colours of the legend for the three geom_line() do not correspond with the true colours for the different geom_line(), and some lines are dashed.
Does anyone know how to solve this?
Plot using Duck's advice
Try this approach. As no data was shared I can test it but it can address in right path:
library(ggplot2)
#Code
Plot_legend <- ggplot(df, aes(x=X, y=Y, colour=ID)) +
geom_point(size=1.5,alpha=0.2) +
geom_line(aes(y=predict(model,df.Z_low), group=ID, linetype = c("1")),
size=1.5, alpha=0.6, color = line_colors[3]) +
geom_line(aes(y=predict(model,df.Z_medium), group=ID, linetype = c("2")),
size=1.5, alpha=0.6, color = line_colors[2]) +
geom_line(aes(y=predict(model,df.Z_high), group=ID, linetype = c("3")),
size=1.5, alpha=0.6, color = line_colors[1]) +
geom_abline(aes(slope=1,intercept=0),linetype="dashed",color="grey52",size=1.5) +
theme_bw() +
scale_linetype_manual(values=c('solid','solid','solid'))+
scale_color_manual(values=c(line_colors[3],line_colors[2],line_colors[1]))+
labs(linetype='Z')
theme(legend.text=element_text(size=18),
legend.title = element_text(size=19, face = "bold",hjust = 0.5),
legend.key=element_blank(),
legend.background = element_rect(colour = 'black', fill = 'white', size = 1, linetype='solid')) +
guides(color=guide_legend(override.aes=list(fill=NA)))
I used next code finally:
Plot_legend <- ggplot(df, aes(x=X, y=Y, colour=ID)) +
geom_point(size=1.5,alpha=0.2) +
geom_abline(aes(slope=1,intercept=0),linetype="dashed",color="grey52",size=1.5) +
theme_bw() +
theme(legend.text=element_text(size=18),
legend.title = element_text(size=19, face = "bold",hjust = 0.5),
legend.key=element_blank(),
legend.background = element_rect(colour = 'black', fill = 'white', size = 1, linetype='solid')) +
guides(color=guide_legend(override.aes=list(fill=NA)))
Plot_legend
Plot_legend_2 <- Plot_legend +
geom_line(aes(y=predict(model,df.Z_low), group=ID, linetype = "m1"), size=1.5, alpha=0.6, color = line_colors[3]) +
geom_line(aes(y=predict(model,df.Z_medium), group=ID, linetype ="m2"), size=1.5, alpha=0.6, color = line_colors[2]) +
geom_line(aes(y=predict(model,df.Z_high), group=ID, linetype ="m3"), size=1.5, alpha=0.6, color = line_colors[1]) +
scale_linetype_manual(values = c(m1 = "solid", m2 = "solid", m3 = "solid"),labels = c(m1 = "1", m2 = "2", m3 = "3")) +
labs(color = "ID", linetype = expression(Z)) +
guides(linetype = guide_legend(override.aes = list(color = line_colors)))
Plot_legend_2

R ggplot(): geom_point() with color-palette "Greens" , how to get black point border?

I plot a scatter plot with ggplot() and use a certain color palette, namely 'Greens'. Basically I am very happy with the plot, but I would like to have a black border around each point. My code for the plot is:
p <- ggplot(data = df.dataCorrelation, aes(x = prod1, y = prod2)) +
geom_point(aes(color = year)) +
geom_smooth(method = "lm", se = FALSE, color = "#007d3c") +
theme_classic() +
theme(legend.position = "none") +
theme(panel.background = element_blank()) +
scale_color_brewer(palette = 'Greens') + # customized color palette
xlab(product1) +
ylab(product2) +
ggtitle("Correlation Scatter Plot (Pearson)") +
theme(plot.title = element_text(hjust = 0.5, face = "bold"))
and provides the following graphic:
I know that I can draw black borders with the command:
geom_point(aes(color = year, fill = ?), color = "black", pch = 21),
but that doesn't work with my selected color palette because I don't know what to use in fill = ?
Try with this.
Here data for a reproducible example
library(dplyr)
product1 <- "product1"
product2 <- "product2"
df.dataCorrelation <- iris %>% rename(prod1 = Petal.Length,
prod2 = Petal.Width,
year = Species)
Here your code
library(ggplot2)
ggplot(data = df.dataCorrelation, aes(x = prod1, y = prod2)) +
geom_point(aes(fill = year), colour = "black", shape = 21, size = 3) +
geom_smooth(method = "lm", se = FALSE, color = "#007d3c") +
theme_classic() +
theme(legend.position = "none") +
theme(panel.background = element_blank()) +
scale_fill_brewer(palette = 'Greens') + # customized color palette
xlab(product1) +
ylab(product2) +
ggtitle("Correlation Scatter Plot (Pearson)") +
theme(plot.title = element_text(hjust = 0.5, face = "bold"))
NOTE that:
I wrote colour = "black"
I changed scale_colour_brewer to scale_fill_brewer
I wrote fill = year instead of colour = year
(I increased the size of the points only because I couldn't see the final result)

Resources