legend to show multiple layers (ggplot) - r

I'm trying to show both the geom_line and the geom_point in the legend, however I can't seem to get the geom_line to appear.
graph <- ggplot(mar, aes(x=long, y=lat)) + xlab("Longitude") + ylab("Latitude") + labs(size = "Distance from predicted \n to known Roman road (m)")
graph + theme_light() + geom_point(aes(size=distance$NEAR_DIST)) + geom_line(color="white", size=0.5)
This generates a graph with geom_point (size of points are based on distance from the line in geom_line and another line), but I can't get the geom_line to appear in the legend. Any ideas on how to do this?

Answered by Craig:
graph <- ggplot(mar, aes(x=long, y=lat)) + xlab("Longitude") + ylab("Latitude") + labs(size = "Distance from predicted \n to known Roman road (m)")
graph + theme_dark() + geom_point(aes(size=distance$NEAR_DIST)) + geom_line(aes(color = "LCP Roman Road"), size = 0.5) + scale_color_manual(name = "tt", values = "white")
assigned color via an aesthetic.

Related

Labels not appearing in x-axis of second graph when using ggarange

this is my first post here, I'm having issues with getting the labels on the x axis of my second plot to show up when using ggarange, but they show up fine when I run them separately in R. Would anyone be able to give me some advice as to how I can fix this? Thanks in advance.
This is my code:
Plot 1
species_bias<- ggplot(Obs_Bias,aes(x=Species,y=Observations, fill=Species))+
geom_boxplot() +
stat_summary(fun = mean)+
theme_classic()+
ggtitle("Species Bias")+
theme(legend.position = "none")+
ylab("Relative Abundance")
species_bias
Plot 2
Abundace_PLOT<- ggplot(Abundance_Errorbar, aes(x=Species, y=Mean,fill=Method)) +
geom_bar(stat="identity", position=position_dodge()) +
geom_errorbar(aes(ymin=Mean-SE, ymax=Mean+SE),width=.2, position=position_dodge(0.9)) +
labs(x="Species", y="Relative Abundnace") +
theme_classic() +
ggtitle("Relative Abundance in Plastifauna grouped by Survey Method")
Abundace_PLOT
Combined plots on page
Species_Bias_ggarange<-ggarrange(species_bias,Abundace_PLOT + rremove("x.text"), labels = c("A","B"), ncol = 2, nrow = 1)
annotate_figure(Species_Bias_ggarange, top=text_grob("Visualizing Species Bias", face="bold",size=14))
Species_Bias_ggarange

How to show the part of the errorbar lines which are within the plot margins using `ggplot2`?

I have a grid of plots, all with the same y and x-axis scale. The plots represent time in the x-axe and mean values in the y-axe with their standard errors. My problem is that some errorbars are not entirely within the plot margins, and I wonder if there is some way to represent the part of the errorlines that are within the plot margins. Below I give a fake example and code to play with:
df <- data.frame(time=seq(-15,15,1),
mean=c(0.49,0.5,0.53,0.55,0.57,0.59,0.61,0.63,0.65,0.67,0.69,0.71,0.73,0.75,0.77,0.79,0.77,0.75,0.73,0.71,0.69,0.67,0.65,0.63,0.61,0.59,0.57,0.55,0.53,0.51,0.49),
sd=c(0.09,0.087,0.082,0.08,0.023,0.011,0.010,0.009,0.008,0.007,0.006,0.005,0.004,0.003,0.002,0.001,0.002,0.003,0.004,0.005,0.006,0.007,0.008,0.009,0.010,0.011,0.023,0.08,0.084,0.087,0.09))
Plot <- ggplot(df, aes(x=time, y=mean)) +
geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.3) +
geom_point(size=1) +
geom_line () +
theme_bw() +
scale_y_continuous(limits = c(0.49, 0.85), breaks = c(0.5, 0.65,0.8))
Plot
You need to set coord_cartesian limits rather than scale_y_continuous limits:
ggplot(df, aes(x=time, y=mean)) +
geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.3) +
geom_point(size=1) +
geom_line () +
theme_bw() +
scale_y_continuous(breaks = c(0.5, 0.65,0.8)) +
coord_cartesian(ylim = c(0.49, 0.85))

Custom legend for geom_boxplot with connective mean line

I have combined ggplot boxplots with a connecting line which is the mean average.
How could I create a legend so people know the blue circle points represent the mean average for each boxplot?
library(ggplot2)
library(scales)
options(scipen=11)
ggplot(Price, aes(x=Price$stage_code, y=Price$Realvalue)) +
scale_y_continuous(labels = comma) +
geom_boxplot(notch=FALSE, outlier.shape=NA, fill="red", alpha=0.2) +
coord_cartesian(ylim=c(0,1000000000)) +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
ggtitle("Average True Value of Listed Mining Companies\nThroughout Mine Development Stages") +
xlab("Project Development Stages") +
ylab("Number of Diluted Stocks x Closing Stock Price") +
stat_summary(fun.y=mean, geom="line", linetype="dotted",
size=1.4, color = "Blue",alpha=0.6, aes(group=1)) +
stat_summary(fun.y=mean, geom="point", alpha=1, color="darkblue",
size=3.2, shape = 21, fill = "lightblue", stroke = 2)
ggplot2 only adds legends for colors assigned based on variables.
edit: I realized from this answer that the legend can be added manually. This is a much better approach.
Just map the color within aes, and use scale_color_manual to add a title and specify the colors:
stat_summary(aes(color="Legend"),fun.y=mean, geom="point", alpha=1,
size=3.2, shape = 21, fill = "lightblue", stroke = 2) +
scale_colour_manual("Legend title", values="darkblue")

How to make geom_abline show_guide line types show up in legend correctly

set.seed(586)
data<-data.frame(x=sort(runif(20)),y=sort((rnorm(1)*1:20*.234)),grp=factor(sample(c(0,1),20,replace = T)))
ggplot(data, aes(x=x, y=y, shape=grp)) +
geom_point() +
theme_classic() +
scale_shape_manual("PT Status",
values=c(1,3),
breaks=c(0,1),
labels=c("No","Yes"))+
scale_x_continuous("My x") +
scale_y_continuous("My y")+
geom_abline(intercept=.12, slope=.98,linetype=1,show_guide = TRUE)+
geom_abline(intercept=.05, slope=(-.3+.98),linetype=3,show_guide = TRUE)+
theme(legend.position="bottom")
Lines look right, and I like how the lines are integrated into the legend. But obviously in my code I'm not specifying what data go to which abline. Is there a way to simply indicate this in the geom_abline code, or some other way to recode it to make it so that the first one is solid and the second is dashed, in terms of the legend?
Using #Jorans suggestion I created
smDf<-data.frame(intercept=c(.12,.05),slope=c(.98, (-.3+.98)),linetype=factor(c(1,3)))
Then the new code is:
ggplot(data, aes(x=x, y=y, shape=grp)) +
geom_point() +
theme_classic() +
scale_shape_manual("PT Status",
values=c(1,3),
breaks=c(0,1),
labels=c("No","Yes"))+
scale_x_continuous("My x") +
scale_y_continuous("My y")+
geom_abline(aes(intercept=intercept, slope=slope, linetype=linetype), data=smDf, show_guide = TRUE)
Which gives me:
So now how do I integrate these two?
This could be better documented, I think, but you basically need to give ggplot manual scales of the same basic structure for them to be merged:
ggplot() +
geom_point(data = data,aes(x=x, y=y, shape=grp)) +
geom_abline(aes(intercept=intercept, slope=slope, linetype=linetype), data=smDf,show_guide = TRUE) +
theme_classic() +
scale_shape_manual(name = "PT Status",
values=c(1,3),
breaks=c(0,1),
labels=c("No","Yes"))+
scale_linetype_manual(name = "PT Status",
values=c(1,3),
labels=c("No","Yes"))+
scale_x_continuous("My x") +
scale_y_continuous("My y")

ggplot: manual color assignment for single variable only

I have this plot:
ggplot(data3, aes(year, NY.GDP.MKTP.KD.ZG, color = country)) + geom_line() +
xlab('Year') + ylab('GDP per capita')
labs(title = "Annual GDP Growth rate (%)") +
theme_bw()
Now I want to change color and line thickness (black, and a about 30% thicker than others) for one variable only (for one country only).
I have found how to manually assign colors for all variables, but not how to do it for only one. Also, graph can have different number of variables (countries), depending on input data.
A bit difficult without some reproducible data, but you should be able to achieve this by adding a geom_line() that only uses the data for that specific country:
ggplot(data3, aes(year, NY.GDP.MKTP.KD.ZG, color = country)) + geom_line() +
xlab('Year') + ylab('GDP per capita') +
labs(title = "Annual GDP Growth rate (%)") +
theme_bw() +
geom_line(data=subset(data3, country == "China"), colour="black", size=1.5)
Keeping the legend in line with the colour and size is a bit trickier- you can do it by manually hacking at the legend with override.aes, but it's not necessarily the most elegant solution:
# Needed to access hue_pal(), which is where ggplot's
# default colours come from
library(scales)
ggplot(data3, aes(year, NY.GDP.MKTP.KD.ZG, color = country)) + geom_line() +
xlab('Year') + ylab('GDP per capita') +
labs(title = "Annual GDP Growth rate (%)") +
theme_bw() +
geom_line(data=subset(data3, country == "World"), colour="black", size=1.5) +
guides(colour=guide_legend(override.aes=list(
colour=c(hue_pal()(11)[1:10], "black"), size=c(rep(1, 10), 1.5))))

Resources