Adding Legend Label for Hline ggplot2 - r

I am trying to add a legend to ggplot2 based on some horizontal comparison lines that were added in. My code currently looks like this
aplot <- ggplot(aData, aes(x = DEP, y = DECAY, color = GENDER))
aplot +
geom_point() +
geom_smooth(method = "lm", se = FALSE) +
geom_hline(yintercept = meanCD, color = "purple")+
geom_hline(yintercept = medianCD, color = "forestgreen") +
geom_hline(yintercept = medianSAD, color = "goldenrod3", linetype = "dashed")+
geom_hline(yintercept = meanSAD, color = "deeppink", linetype = "dashed")
meanCD, medianCD, meanSD, medianSD are all stored as seperate values and I need to add them to the graph for comparitive purposes. aData is just a bunch of points. I cannot get a legend to show up giving the color of the line and giving an appropriate label and I am unsure how to accomplish this in ggplot2.

Related

Is there a way to change the symbol shape in a ggplot2 legend?

I made a plot using ggplot in R and wanted to have labels with the values that correspond with each of the points on the plot. I used the function geom_label_repel to get the labels on the plot, but it seems like it changed the legend to a letter instead of a dot, which I don't really like. Is there a way to change the shape of the symbol in the legend to a dot instead?
Here's the code for my plot:
ggplot(CI_bar_df_null, mapping = aes(x = model, y = R2, color = condition, group = condition)) +
geom_point() +
geom_line() +
geom_label_repel(
label = CI_bar_df_null$R2factor,
nudge_x = .3, nudge_y = 0) +
geom_errorbar(aes(ymin = CI_lower, ymax = CI_upper), width = .3) +
#ylim(-.06, .6)
ggtitle('Model R-Squared Values and Confidence Intervals') +
ylab('R-Squared Value') +
xlab('Model Type') +
scale_color_discrete(name = "Condition") +
scale_shape_discrete(shape = 17)
You can simply add the show.legend = F argument inside geom_label_repel. This will avoid creating a legend for geom_label_repel and leave intact the other two legends (geom_point and geom_line).
geom_label_repel(
label = mtcars$cyl,
nudge_x = .3,
nudge_y = 0,
show.legend = F)

How to show the color and opacity in legend in ggplot2?

This is a plot that I'm trying to create like the one that was shown in nytimes.
My code:
ggplot(gwsj, aes(x = Year, y = Freq, color = Gender)) +
geom_line(size = 1.2, aes(alpha = Functn)) +
geom_point(aes(alpha = Functn)) +
scale_color_manual(values = c("Female" = "#d81b60", "Male" = "#1976d2")) +
facet_wrap(~OrgType, scales = "free_y") +
theme_pubclean()
What I get:
What I want
The scale that shows the gender count and the Functn legend with colors and opacity like the ones shown in nytimes. I've tried many things, but I'm missing something somewhere

Adding legend for combo bar and line graph -- ggplot ignoring commands

I am trying to make a bar chart with line plots as well. The graph has created fine but the legend does not want to add the line plots to the legend.
I have tried so many different ways of adding these to the legend including:
ggplot Legend Bar and Line in Same Graph
None of which have worked. show.legend also seems to have been ignored in the geom_line aes.
My code to create the graph is as follows:
ggplot(first_q, aes(fill = Segments)) +
geom_bar(aes(x= Segments, y= number_of_new_customers), stat =
"identity") + theme(axis.text.x = element_blank()) +
scale_y_continuous(expand = c(0, 0), limits = c(0,3000)) +
ylab('Number of Customers') + xlab('Segments') +
ggtitle('Number Customers in Q1 by Segments') +theme(plot.title =
element_text(hjust = 0.5)) +
geom_line(aes(x= Segments, y=count) ,stat="identity",
group = 1, size = 1.5, colour = "darkred", alpha = 0.9, show.legend =
TRUE) +
geom_line(aes(x= Segments, y=bond_count)
,stat="identity", group = 1, size = 1.5, colour = "blue", alpha =
0.9) +
geom_line(aes(x= Segments, y=variable_count)
,stat="identity", group = 1, size = 1.5, colour = "darkgreen",
alpha = 0.9) +
geom_line(aes(x= Segments, y=children_count)
,stat="identity", group = 1, size = 1.5, colour = "orange", alpha
= 0.9) +
guides(fill=guide_legend(title="Segments")) +
scale_color_discrete(name = "Prod", labels = c("count", "bond_count", "variable_count", "children_count)))
I am fairly new to R so if any further information is required or if this question could be better represented then please let me know.
Any help is greatly appreciated.
Alright, you need to remove a little bit of your stuff. I used the mtcars dataset, since you did not provide yours. I tried to keep your variable names and reduced the plot to necessary parts. The code is as follows:
first_q <- mtcars
first_q$Segments <- mtcars$mpg
first_q$val <- seq(1,nrow(mtcars))
first_q$number_of_new_costumers <- mtcars$hp
first_q$type <- "Line"
ggplot(first_q) +
geom_bar(aes(x= Segments, y= number_of_new_costumers, fill = "Bar"), stat =
"identity") + theme(axis.text.x = element_blank()) +
scale_y_continuous(expand = c(0, 0), limits = c(0,3000)) +
geom_line(aes(x=Segments,y=val, linetype="Line"))+
geom_line(aes(x=Segments,y=disp, linetype="next line"))
The answer you linked already gave the answer, but i try to explain. You want to plot the legend by using different properties of your data. So if you want to use different lines, you can declare this in your aes. This is what get's shown in your legend. So i used two different geom_lines here. Since the aes is both linetype, both get shown at the legend linetype.
the plot:
You can adapt this easily to your use. Make sure you using known keywords for the aesthetic if you want to solve it this way. Also you can change the title names afterwards by using:
labs(fill = "costum name")
If you want to add colours and the same line types, you can do customizing by using scale_linetype_manual like follows (i did not use fill for the bars this time):
library(ggplot2)
first_q <- mtcars
first_q$Segments <- mtcars$mpg
first_q$val <- seq(1,nrow(mtcars))
first_q$number_of_new_costumers <- mtcars$hp
first_q$type <- "Line"
cols = c("red", "green")
ggplot(first_q) +
geom_bar(aes(x= Segments, y= number_of_new_costumers), stat =
"identity") + theme(axis.text.x = element_blank()) +
scale_y_continuous(expand = c(0, 0), limits = c(0,3000)) +
geom_line(aes(x=Segments,y=val, linetype="solid"), color = "red", alpha = 0.4)+
geom_line(aes(x=Segments,y=disp, linetype="second"), color ="green", alpha = 0.5)+
scale_linetype_manual(values = c("solid","solid"),
guide = guide_legend(override.aes = list(colour = cols)))

Add geom_hline to legend

After searching the web both yesterday and today, the only way I get a legend working was to follow the solution by 'Brian Diggs' in this post:
Add legend to ggplot2 line plot
Which gives me the following code:
library(ggplot2)
ggplot()+
geom_line(data=myDf, aes(x=count, y=mean, color="TrueMean"))+
geom_hline(yintercept = myTrueMean, color="SampleMean")+
scale_colour_manual("",breaks=c("SampleMean", "TrueMean"),values=c("red","blue"))+
labs(title = "Plot showing convergens of Mean", x="Index", y="Mean")+
theme_minimal()
Everything works just fine if I remove the color of the hline, but if I add a value in the color of hline that is not an actual color (like "SampleMean") I get an error that it's not a color (only for the hline).
How can adding a such common thing as a legend big such a big problem? There much be an easier way?
To create the original data:
#Initial variables
myAlpha=2
myBeta=2
successes=14
n=20
fails=n-successes
#Posterior values
postAlpha=myAlpha+successes
postBeta=myBeta+fails
#Calculating the mean and SD
myTrueMean=(myAlpha+successes)/(myAlpha+successes+myBeta+fails)
myTrueSD=sqrt(((myAlpha+successes)*(myBeta+fails))/((myAlpha+successes+myBeta+fails)^2*(myAlpha+successes+myBeta+fails+1)))
#Simulate the data
simulateBeta=function(n,tmpAlpha,tmpBeta){
tmpValues=rbeta(n, tmpAlpha, tmpBeta)
tmpMean=mean(tmpValues)
tmpSD=sd(tmpValues)
returnVector=c(count=n, mean=tmpMean, sd=tmpSD)
return(returnVector)
}
#Make a df for the data
myDf=data.frame(t(sapply(2:10000, simulateBeta, postAlpha, postBeta)))
Given solution works in most of the cases, but not for geom_hline (vline). For them you usually don't have to use aes, but when you need to generate a legend then you have to wrap them within aes:
library(ggplot2)
ggplot() +
geom_line(aes(count, mean, color = "TrueMean"), myDf) +
geom_hline(aes(yintercept = myTrueMean, color = "SampleMean")) +
scale_colour_manual(values = c("red", "blue")) +
labs(title = "Plot showing convergens of Mean",
x = "Index",
y = "Mean",
color = NULL) +
theme_minimal()
Seeing original data you can use geom_point for better visualisation (also added some theme changes):
ggplot() +
geom_point(aes(count, mean, color = "Observed"), myDf,
alpha = 0.3, size = 0.7) +
geom_hline(aes(yintercept = myTrueMean, color = "Expected"),
linetype = 2, size = 0.5) +
scale_colour_manual(values = c("blue", "red")) +
labs(title = "Plot showing convergens of Mean",
x = "Index",
y = "Mean",
color = "Mean type") +
theme_minimal() +
guides(color = guide_legend(override.aes = list(
linetype = 0, size = 4, shape = 15, alpha = 1))
)

R ggplot combine legends for colour and fill with different factor length

I am making a plot with data from an incomplete factorial design. Due to the design, I have different length for the manual scale for colour and the manual scale for fill. Thus, I get two legends. How could I delete one of them or even better combine them?
I have looked at those questions:
Merge separate size and fill legends in ggplot
How to merge color, line style and shape legends in ggplot
How to combine scales for colour and size into one legend?
However, the answers did not help me as they did not handle incomplete designs.
Here is some example data and the plot I produced so far:
#Example data
Man1 <- c(25,25,30,30,30,30,35,35,40,40,40,40,45,45)
Man2 <- c(25,25,30,30,40,40,35,35,40,40,30,30,45,45)
DV <- c(24.8,25.2,29.9,30.3,35.2,35.7,34,35.1,40.3,39.8,35.8,35.9,44,44.8)
Data <- data.frame(Man1,Man2,DV)
#Plot
ggplot(data = Data, aes(x = Man1, y = DV, group=as.factor(Man2), colour=as.factor(Man2))) +
theme_bw() +
geom_abline(intercept = 0, slope = 1, linetype = "longdash") +
geom_point(position = position_dodge(1))
geom_smooth(method = "lm", aes(x = Man1, y = DV, group=as.factor(Man2), fill=as.factor(Man2))) +
scale_colour_manual(name = "Man2", values=c('grey20', 'blue','grey20','tomato3', 'grey20')) +
scale_fill_manual(name = "Man2", values=c('blue','tomato3'))
This gives me the following picture:
ggplot of incomplete design with two legends
Could someone give me a hint how to delete one of the legends or even better combine them? I would appreciate it!
By default the scale drops unused factor levels, which is relevant here because can only get lines for a couple of your groups.
You can use drop = FALSE to change this in the appropriate scale_*_manual() (which is for fill here).
Then use the same vector of colors for both the fill and color scales. I usually make a named vector for this.
# Make vector of colors
colors = c("25" = 'grey20', "30" = 'blue', "35" = 'grey20', "40" = 'tomato3', "45" = 'grey20')
#Plot
ggplot(data = Data, aes(x = Man1, y = DV, group=as.factor(Man2), colour= as.factor(Man2))) +
theme_bw() +
geom_abline(intercept = 0, slope = 1, linetype = "longdash") +
geom_point(position = position_dodge(1)) +
geom_smooth(method = "lm", aes(fill=as.factor(Man2))) +
scale_colour_manual(name = "Man2", values = colors) +
scale_fill_manual(name = "Man2", values = colors, drop = FALSE)
Alternatively, use guide = "none" to remove the fill legend all together.
ggplot(data = Data, aes(x = Man1, y = DV, group=as.factor(Man2), colour= as.factor(Man2))) +
theme_bw() +
geom_abline(intercept = 0, slope = 1, linetype = "longdash") +
geom_point(position = position_dodge(1)) +
geom_smooth(method = "lm", aes(fill=as.factor(Man2))) +
scale_colour_manual(name = "Man2", values = colors) +
scale_fill_manual(name = "Man2", values=c('blue','tomato3'), guide = "none")

Resources