Draw a box around a legend ggplot2 - r

I created a plot with a custom legend in ggplot2. I tried to draw a box around all the items in the legend, however I could only draw a box around each individual item. How can I create only one box around all the items?
library(ggplot2)
ggplot(mpg, aes(displ, cty)) +
geom_point(aes(shape = "Data")) +
stat_smooth(aes(linetype = "Regression"), method = "lm",
formula = y ~ x, se = FALSE, colour = 1, size = 0.5) +
scale_shape_manual(values = 1) +
labs(shape = "", linetype = "") +
theme_classic() +
theme(panel.border = element_rect(colour = "black", fill=NA),
aspect.ratio = 1, axis.text = element_text(colour = 1, size = 12),
legend.background = element_rect(linetype = 2, size = 0.5, colour = 1))

It seems that the legend.background rectangle overlaps the legend.box.background rectangle. An easy fix is to set legend.background = element_blank().
But then, in my opinion, the spacing in the legend is ugly. The legend titles take up too much space even with no title set. Fix this be setting legend.title = element_blank(). Also the spacing between the two legends is too large. Fix this by setting the space to zero legend.spacing.y = unit(0, "mm")
library(ggplot2)
ggplot(mpg, aes(displ, cty)) +
geom_point(aes(shape = "Data")) +
stat_smooth(aes(linetype = "Regression"), method = "lm",
formula = y ~ x, se = FALSE, colour = 1, size = 0.5) +
scale_shape_manual(values = 1) +
labs(shape = "", linetype = "") +
theme_classic() +
theme(legend.title = element_blank(),
legend.spacing.y = unit(0, "mm"),
panel.border = element_rect(colour = "black", fill=NA),
aspect.ratio = 1, axis.text = element_text(colour = 1, size = 12),
legend.background = element_blank(),
legend.box.background = element_rect(colour = "black"))

Related

How can I completely remove legend.key from ggplot2 legend?

I'm plotting a graph and I need to completely remove the legend.key from my ggplot legend. Why I need to do this? The legend starts with a number that reference the X axis breaks, and the label its too large and I don't want to keep it in the X axis. So, in the X axis i put breaks=1:15, and in legend the label starts with this numbers.
In resume, I just want to remove the legend.key from my graph. Is it possible? I have tried legend.key=element_blank(), but without sucess.
Obs.: In the code is it possible to see that I don't want the fill=legto change the colors of each bar. Everything is set to be gray and I just want to remove de legend.key.
ggplot(IC_QS, aes(x=ind,y=values))+
geom_boxplot(aes(fill=leg),color="black", outlier.colour = "red")+
labs(title = "XXXXXXXXXX",
subtitle = "XXXXXXXXXXX",
caption = "XXXXXXXXXXXXX")+
scale_x_discrete(name = "", labels=1:15)+
scale_y_continuous(name = "XXX", breaks = seq(0,10,1), expand = c(0,0.08*max(IC_QS$values)))+
scale_fill_manual(name="Sectors", values = rep("gray", 15), labels=str_wrap(IC_QS_leg,25))+
theme(legend.position = "right", legend.background = element_blank(),
legend.key = element_blank(),legend.text = element_text(face = "bold", size = 8,),
panel.background = element_blank(), panel.grid.major = element_line(colour = "gray", linetype = "dashed"),
axis.title.x = element_text(face = "bold",vjust = -1), axis.title.y = element_text(face="bold", vjust = +1.5),
axis.text = element_text(colour="black", face = "bold"), title = element_text(face = "bold"))
Obviously we don't have your data, but here's an idea using the iris built-in data set
ggplot(iris, aes(Species, Petal.Width, fill = Species)) +
geom_boxplot() +
scale_x_discrete(labels = seq(length(levels(iris$Species)))) +
scale_fill_manual(values = rep("grey", length(levels(iris$Species))),
labels = paste(seq(length(levels(iris$Species))),
levels(iris$Species), sep = " - ")) +
guides(fill = guide_legend(override.aes = list(color = NA, fill = NA))) +
theme_light(base_size = 16) +
theme(legend.key.width = unit(0, "mm"))

Increase Vertical Spacing between Legend Key in ggplot2

How can I increase vertical spacing between legend keys:
p1 <- ggplot(data = HSS, mapping = aes(x = EVENT, y = HSS, fill = TIME)) +
geom_bar(stat = "identity",width=0.7, colour = "black", position = position_dodge(0.7)) +
scale_fill_manual("HSS", values = c("deepskyblue3", "indianred2"),
labels = c("1200 UTC (0.049)", "0000 UTC (0.031)")) + theme_bw()
p1 <- p1 + scale_y_continuous(expand = expansion(mult = c(0.0085, -0.085)),
limits = c(-0.03,0.5), breaks = c(-0.03,-0.01, 0.01, 0.03, 0.05, 0.07,0.09,0.11,0.13,0.15,0.17,
0.19, 0.21,0.23,0.25,0.27,0.29,0.31,0.33,0.45),
labels = c("-0.03","-0.01","0.01","0.03","0.05","0.07","0.09","0.11","0.13","0.15","0.17",
"0.19","0.21","0.23","0.25","0.27","0.29","0.31","0.33","0.45")) +
theme(axis.text.x=element_text(color = "black", size=12, face = "bold", angle=90, vjust=.5,
hjust=0.8)) +
theme(axis.text.y = element_text(color = "black", size=12, face = "bold"))
p1 <- p1 + theme( axis.line = element_line(colour = "black", size = 0.5, linetype = "solid")) +
labs( y = "HSS")
p1 <- p1 + theme(axis.title=element_text(colour = "blue2" ,size=14,face="bold", vjust = 0.1))
p1 <- p1 + theme(legend.position=c(0.98,0.98)) + theme(legend.title=element_blank(),
legend.text = element_text(face = "bold", size = "12"),
legend.box.background = element_rect(size=0.7, linetype="solid"),
legend.justification = c("right", "top"),
legend.box.margin = margin(1, 1, 1, 1)
)
p1
I tried using legend.key.height legend.spacing.y guide but it only stretched legend keys without adding space between them. Also how can I remove alternate lables (encircled) of Y-axis keeping tickmark with plot.
After browsing ggplot2's source code for a bit, I come to the conclusion that the legend.spacing.y is only applied when the byrow = TRUE as argument to the legend.
Simplied example below.
library(ggplot2)
ggplot(iris, aes(Sepal.Width)) +
geom_density(aes(fill = Species)) +
guides(fill = guide_legend(byrow = TRUE)) +
theme(legend.spacing.y = unit(1, "cm"))
With regards to the labels, just remove the values from the breaks argument in scale_y_continuous() that you don't want to show, you're already specifying them manually.

Adjusting legend.title ,legend.text and legend color in ggplot2

I am unable to change the color of the Segmentation legend in the plot. I need two different colors for it as a text in the legend and as well as in the visual plot.
er<- ggmap(sq_map2) +
geom_point(data = sisquoc, size = 3, aes(fill = Segmentation)) +
geom_line(data = sisquoc, size = 3, aes(color =SpeedMeterPerSecond)) +
geom_text(data = sisquoc, aes(label = paste(" ",
as.character(Location_ids), sep="")),
angle = 60, hjust = 0, color = "sienna4",size = 6 )
gg<- er + labs(x ="Longitude", y = "Latitude") +
theme(axis.title = element_text(size=20),
panel.background = element_rect(fill = "white",size = 0.5, linetype =
"dotted"),
panel.grid.major = element_line(size = 0.5, linetype = 'dotted',colour
= "black"),
panel.grid.minor = element_line(size = 0.5, linetype = 'dotted',colour
= "black"),
panel.border = element_rect(colour = "black", fill=NA, size=0.5),
axis.text.y = element_text(size=18),
axis.text.x = element_text(size=18))
gg + theme(legend.position="right",
legend.title = element_text(colour="Black", size=18),
legend.text = element_text(colour="black", size = 15),
legend.background = element_rect(fill="grey90",
size=0.5, linetype="solid",
colour ="black")) + scale_color_continuous(name="Speed (m/s)\n")
Something like the following should work.
Just specify the legend title explicitly and add \n at the end of the string, which adds an extra blank row:
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, col=Petal.Length))+
geom_point() + scale_color_continuous(name="my scale\n")
Alternatively you could try changing the legend orientation, which
however usually is most compact when the legend is at the bottom.
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, col=Petal.Length))+
geom_point() + theme(legend.direction = "horizontal", legend.position = "bottom")

Labeling with geom_text and geom_text_repel

I am trying to put labels using Geom Text. If i use geom_text, i cant see all values. But if i use geom_text_repel, i see all values with duplication. The purpose is to see label all the unique values without any duplication. Can anyone please tell me how it will be done ?
library(ggrepel)
library(ggplot2)
rr <- ggplot(data = staypoint6, aes(staypoints.Stayplon,
staypoints.staypLat))+
geom_line(alpha = 0.5, size = 2, shape = 16, width = 0.000003, height =
0.000003, colour ="darkgoldenrod4") + coord_fixed (ratio = 2) +
labs(x ="Longitude", y = "Latitude") +
theme(axis.title = element_text(size=14),
panel.background = element_rect(fill = "white",size = 0.5, linetype = "dotted"),
panel.grid.major = element_line(size = 0.5, linetype = 'dotted',colour = "black"),
panel.grid.minor = element_line(size = 0.5, linetype = 'dotted',colour = "black"),
panel.border = element_rect(colour = "black", fill=NA, size=0.5),
axis.text.y = element_text(size=12),
axis.text.x = element_text(size=12)) + geom_text(aes(label =
Location_ids), colour = "dodgerblue4", size=6)
rr + geom_text(aes(label = paste0("(", staypoint6$arri_time, ",",
staypoint6$lev_time, ")")), check_overlap = FALSE, size=4, hjust=0.15,
vjust=2)
rr + geom_text_repel(aes(label = paste0("(", staypoint6$arri_time, ",",
staypoint6$lev_time, ")")), check_overlap = FALSE, size=4, hjust=0.15, vjust=2)

Geom point visualization issue in R

This is question linked to previous question (Adjusting legend.title ,legend.text and legend color in ggplot2). I am having issue to change color of the geom points (Run and Walk Segmentation) in the plot. Can anyone please help me in this ? Is there any other way that i can have more better visualizations for the segmentation ? Thanks
er<- ggmap(sq_map2) +
geom_point(data = sisquoc, size = 8, aes(fill = Segmentation)) +
geom_line(data = sisquoc, size = 3, aes(color =SpeedMeterPerSecond)) +
geom_text(data = sisquoc, aes(label = paste(" ",
as.character(Location_ids),
sep="")),
angle = 60, hjust = 0, color = "sienna4",size = 6 )
gg<- er + labs(x ="Longitude", y = "Latitude") +
theme(axis.title = element_text(size=20),
panel.background = element_rect(fill = "white",size = 0.5, linetype =
"dotted"),
panel.grid.major = element_line(size = 0.5, linetype =
'dotted',colour
= "black"),
panel.grid.minor = element_line(size = 0.5, linetype =
'dotted',colour
= "black"),
panel.border = element_rect(colour = "black", fill=NA, size=0.5),
axis.text.y = element_text(size=18),
axis.text.x = element_text(size=18))
gg + theme(legend.position="right",
legend.title = element_text(colour="Black", size=18),
legend.text = element_text(colour="black", size = 15),
legend.background = element_rect(fill="grey90",
size=0.5, linetype="solid",
colour ="black")) +
scale_color_continuous(name="Speed (m/s)\n")
I assume that you want to change the colour of the points in the plot.
try + scale_fill_manual(values = c("Run" = "black","Walk" = "grey"))
For geom_point to make use of aes(fill=...) you have to select shapes that can take fill values in addition to colour values, otherwise geom_point takes aes(colour=...). Fill is the appropriate aes to use here since you are already making use of aes(colour=...) for geom_line.
See possible shapes 21 to 25 that take fill values here
Try:
ggmap(sq_map2) +
geom_point(data = sisquoc, size = 8, aes(fill = Segmentation, shape = Segmentation) +
scale_shape_manual(values=c(21, 24))
You can further define fill values using e.g. scale_fill_manual(values=c("red", "blue"))

Resources