Editing legend in ggplot2 - R - r

I'm learning to use ggplot to make graphs for my research and I'm having some trouble setting legends for them.
Initially I thought about just using the aes() function inside geom_point and geom_line to get the aesthetics I'm looking for. However, I realized the legends weren't being generated by doing it this way. Code and exemple below.
#Stablish the variables as vectors
MexxJan_hydrogen <- c(0, 1.38, 3.19, 8.30)
MexyJan_hydrogen <- c(0, 1.25, 2.78, 6.23)
MexzJan_hydrogen <- c(0, 2.46, 5.68, 12.18)
MexwJan_hydrogen <- c(0, 7.56, 9.20, 10.19)
time_hydrogen <- c(0, 60, 120, 180)
#Create the data frame
hydrogen_data <- data.frame(time_hydrogen, MexxJan_hydrogen, MexyJan_hydrogen, MexzJan_hydrogen, MexwJan_hydrogen)
view(hydrogen_data)
#Code the plot
hydrogen_plot <- ggplot(data = hydrogen_data) +
geom_line(aes(x = time_hydrogen, y = MexxJan_hydrogen), color = "palegreen3", lwd = 1) +
geom_line(aes(x = time_hydrogen, y = MexyJan_hydrogen), color = "tan1", lwd = 1) +
geom_line(aes(x = time_hydrogen, y = MexzJan_hydrogen), color = "tomato2", lwd = 1) +
geom_line(aes(x = time_hydrogen, y = MexwJan_hydrogen), color = "cadetblue", lwd = 1) +
geom_point(aes(x = time_hydrogen, y = MexxJan_hydrogen), color = "palegreen3", shape = 15, size = 5) +
geom_point(aes(x = time_hydrogen, y = MexyJan_hydrogen), color = "tan1", shape = 16, size = 5) +
geom_point(aes(x = time_hydrogen, y = MexzJan_hydrogen), color = "tomato2", shape = 17, size = 5) +
geom_point(aes(x = time_hydrogen, y = MexwJan_hydrogen), color = "cadetblue", shape = 18, size = 5) +
theme_bw() +
theme(axis.text = element_text(family = "Arial", size = 15, color = "black"),
axis.title.x = element_text(family = "Arial", size = 16, margin = margin(t = 15)),
axis.title.y = element_text(family = "Arial", size = 16, margin = margin(r = 15)),axis.line = element_line(color = "black"),
plot.background = element_rect(fill = "transparent", color = NA),
panel.border = element_rect(color = "black"),
panel.background = element_rect(fill = "transparent"),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
axis.ticks.length = unit(0.20, units = "cm"),
legend.background = element_rect(fill = "transparent"),
legend.key = element_rect(fill = "transparent", colour = NA),
legend.position = "top",
legend.key.width = unit(0, unit = "cm"),
legend.key.height = unit(0, unit = "cm"),
legend.title = element_blank(),
legend.text = element_text(size = 13.5),
legend.spacing.x = unit(0.1, "cm"),
legend.text.align = unit(0.05, unit = "cm")) +
labs(x = "Time (min)", y = "Gas Evolution (µmol.g"^-1~")") +
coord_cartesian(ylim = c(0,15), xlim = c(0,180)) +
scale_y_continuous(expand = expansion(mult = c(0.02, 0.02)),
n.breaks = 5) +
scale_x_continuous(expand = expansion(mult = c(0.02, 0.02)),
breaks = c(0, 60, 120, 180))
I then found that I could use the function scale_colors_manual to get the desired colors and show the legend. Also, using scale_colors_manual I managed to change the legend text to a shorter option. Code and exemple below.
#Stablish the variables as vectors
MexxJan_hydrogen <- c(0, 1.38, 3.19, 8.30)
MexyJan_hydrogen <- c(0, 1.25, 2.78, 6.23)
MexzJan_hydrogen <- c(0, 2.46, 5.68, 12.18)
MexwJan_hydrogen <- c(0, 7.56, 9.20, 10.19)
time_hydrogen <- c(0, 60, 120, 180)
#Create the data frame
hydrogen_data <- data.frame(time_hydrogen, MexxJan_hydrogen, MexyJan_hydrogen, MexzJan_hydrogen, MexwJan_hydrogen)
view(hydrogen_data)
hydrogen_plot <- ggplot(data = hydrogen_data) +
geom_line(aes(x = time_hydrogen, y = MexxJan_hydrogen, color = "MexxJan_hydrogen"), lwd = 1) +
geom_line(aes(x = time_hydrogen, y = MexyJan_hydrogen, color = "MexyJan_hydrogen"), lwd = 1) +
geom_line(aes(x = time_hydrogen, y = MexzJan_hydrogen, color = "MexzJan_hydrogen"), lwd = 1) +
geom_line(aes(x = time_hydrogen, y = MexwJan_hydrogen, color = "MexwJan_hydrogen"), lwd = 1) +
geom_point(aes(x = time_hydrogen, y = MexxJan_hydrogen, color = "MexxJan_hydrogen"), shape = 15, size = 5) +
geom_point(aes(x = time_hydrogen, y = MexyJan_hydrogen, color = "MexyJan_hydrogen"), shape = 16, size = 5) +
geom_point(aes(x = time_hydrogen, y = MexzJan_hydrogen, color = "MexzJan_hydrogen"), shape = 17, size = 5) +
geom_point(aes(x = time_hydrogen, y = MexwJan_hydrogen, color = "MexwJan_hydrogen"), shape = 18, size = 5) +
theme_bw() +
theme(axis.text = element_text(family = "Arial", size = 15, color = "black"),
axis.title.x = element_text(family = "Arial", size = 16, margin = margin(t = 15)),
axis.title.y = element_text(family = "Arial", size = 16, margin = margin(r = 15)),axis.line = element_line(color = "black"),
plot.background = element_rect(fill = "transparent", color = NA),
panel.border = element_rect(color = "black"),
panel.background = element_rect(fill = "transparent"),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
axis.ticks.length = unit(0.20, units = "cm"),
legend.background = element_rect(fill = "transparent"),
legend.key = element_rect(fill = "transparent", colour = NA),
legend.position = "top",
legend.key.width = unit(0, unit = "cm"),
legend.key.height = unit(0, unit = "cm"),
legend.title = element_blank(),
legend.text = element_text(size = 13.5),
legend.spacing.x = unit(0.1, "cm"),
legend.text.align = unit(0.05, unit = "cm")) +
labs(x = "Time (min)", y = "Gas Evolution (µmol.g"^-1~")") +
coord_cartesian(ylim = c(0,15), xlim = c(0,180)) + #Limit the size of the plot
scale_y_continuous(expand = expansion(mult = c(0.02, 0.02)),
n.breaks = 5) +
scale_x_continuous(expand = expansion(mult = c(0.02, 0.02)),
breaks = c(0, 60, 120, 180)) +
scale_color_manual(labels = c("15Me-NT", "15Me-nNT", "15Me-NNT", "15Me-nnt"),
values = c("MexxJan_hydrogen" = "palegreen3", "MexyJan_hydrogen" = "tan1", "MexzJan_hydrogen" = "cadetblue", "MexwJan_hydrogen" = "tomato2"))
In this case, I got the colors and the legend. However, as you can see in the image, the legend keys look like a bunch of geometric forms stacked. I couldn't find a way to solve this. Tried using scale_shape_manual but I couldn't get the code right.
May you help me getting this plot some beautiful aesthetics? hehehe
Thank you. Stay safe.

To fix your issue you have to move shape inside aes similar to what you have done for color and afterwards set your shapes via scale_shape_manual. However, you could simplify your approach considerably by first reshaping your data to long or tidy data format. Doing so allows to add your lines and points which just one geom_point and geom_line:
library(tidyr)
library(ggplot2)
hydrogen_data_long <- hydrogen_data %>%
tidyr::pivot_longer(-time_hydrogen, names_to = "hydrogren")
ggplot(hydrogen_data_long, aes(x = time_hydrogen, y = value, color = hydrogren)) +
geom_line(lwd = 1) +
geom_point(aes(shape = hydrogren), size = 5) +
scale_shape_manual(
labels = c("15Me-NT", "15Me-nNT", "15Me-NNT", "15Me-nnt"),
values = c(
"MexxJan_hydrogen" = 15, "MexyJan_hydrogen" = 16,
"MexzJan_hydrogen" = 17, "MexwJan_hydrogen" = 18
)
) +
scale_color_manual(
labels = c("15Me-NT", "15Me-nNT", "15Me-NNT", "15Me-nnt"),
values = c(
"MexxJan_hydrogen" = "palegreen3", "MexyJan_hydrogen" = "tan1",
"MexzJan_hydrogen" = "cadetblue", "MexwJan_hydrogen" = "tomato2"
)
) +
theme_bw() +
theme(
axis.text = element_text(family = "Arial", size = 15, color = "black"),
axis.title.x = element_text(family = "Arial", size = 16, margin = margin(t = 15)),
axis.title.y = element_text(family = "Arial", size = 16, margin = margin(r = 15)),
axis.line = element_line(color = "black"),
plot.background = element_rect(fill = "transparent", color = NA),
panel.border = element_rect(color = "black"),
panel.background = element_rect(fill = "transparent"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.ticks.length = unit(0.20, units = "cm"),
legend.background = element_rect(fill = "transparent"),
legend.key = element_rect(fill = "transparent", colour = NA),
legend.position = "top",
legend.key.width = unit(0, unit = "cm"),
legend.key.height = unit(0, unit = "cm"),
legend.title = element_blank(),
legend.text = element_text(size = 13.5),
legend.spacing.x = unit(0.1, "cm"),
legend.text.align = unit(0.05, unit = "cm")
) +
labs(x = "Time (min)", y = "Gas Evolution (µmol.g"^-1 ~ ")") +
coord_cartesian(ylim = c(0, 15), xlim = c(0, 180)) + # Limit the size of the plot
scale_y_continuous(
expand = expansion(mult = c(0.02, 0.02)),
n.breaks = 5
) +
scale_x_continuous(
expand = expansion(mult = c(0.02, 0.02)),
breaks = c(0, 60, 120, 180)
)

You are making life harder for yourself by passing your data frame in the wrong format. If you pivot to long format, you only need a single geom_line and geom_point. It's also far easier to map your colors and shapes, which will automatically appear in the legend.
Also, try to choose a default theme that's closer to the look you want to achieve to cut down on the number of tweaks you have to make via theme. One of the key things you'll learn in R, as in other languages, is that cutting down code to a minimum makes it easier to change or debug your code later on.
library(tidyverse)
hydrogen_data %>%
pivot_longer(-time_hydrogen) %>%
ggplot(aes(time_hydrogen, value, color = name, shape = name)) +
geom_line(lwd = 1) +
geom_point(size = 5) +
scale_color_manual(values = c("tomato2", "palegreen", "tan1", "cadetblue"),
labels = paste0("15Me-", c("NT", "nNT", "NNT", "nnt"))) +
scale_shape_manual(values = c(18, 15, 16, 17),
labels = paste0("15Me-", c("NT", "nNT", "NNT", "nnt"))) +
scale_y_continuous(expression(Gas~Evolution~(µmol.g^-1)),
expand = expansion(mult = c(0.02, 0.02)), n.breaks = 5) +
scale_x_continuous("Time (min)", expand = expansion(mult = c(0.02, 0.02)),
breaks = c(0, 60, 120, 180)) +
theme_classic(base_size = 16) +
theme(axis.text = element_text(family = "Arial", size = 15, color = "black"),
plot.background = element_blank(),
panel.border = element_rect(color = "black", fill = NA),
panel.background = element_blank(),
axis.ticks.length = unit(0.20, units = "cm"),
legend.background = element_blank(),
legend.position = "top",
legend.title = element_blank()) +
coord_cartesian(ylim = c(0, 15), xlim = c(0, 180))

Related

How to reduce the distance between text lines in ggplot axis?

For one of the presentations, I am trying to make a scatter plot. Here is a similar code I am trying to run for the visualization I would like to have
library(tidyverse)
library(showtext)
library(ggtext)
ggplot(mtcars, aes(x = mpg, y = disp)) +
geom_point(size = 1.5) +
labs(title = "<span style = 'color:#005A9C;'>A vs. B</span>",
x = "B<br>BBBBB<br>BBBBBBBBBB<br>BBBBBBBBBB",
y = "A<br>AAAAA<br>AAAAAAAAAA<br>AAAAAAAAAA",
caption = expression(paste(italic("Source:"), " JJJJJ"))) +
theme_minimal() +
theme(
plot.background = element_rect(fill = "white",colour = NA),
panel.background = element_rect(fill = 'white', colour = 'white'),
panel.border = element_blank(),
legend.position = "none",
plot.title = element_markdown(hjust = 0.5, family = "title", size = 45),
plot.subtitle = element_markdown(hjust = 0.5, family = "subtitle", size = 30), # note that to color numbers differently, I used element_markdown not element_text function
axis.title.x = element_markdown(hjust = 0.5, family = "subtitle", size = 33),
axis.text.x = element_markdown(hjust = 0.5, family = "subtitle", size = 20),
axis.title.y = element_markdown(hjust = 0.5, family = "subtitle", size = 33),
axis.text.y = element_markdown(hjust = 0.5, family = "subtitle", size = 20),
plot.caption = element_text(hjust = 0, size = 21, family = "caption"))
ggsave("plot.png", height = 6, width = 7)
And here is the result;
Now, my question is how to reduce the distance between text lines for the x and y axes?

How to change the position of labels in scale_x_continuous in ggplot2?

I was hoping to receive some guidance on how to reduce the space between labels specified in scale_x_continuous and the x axis. The empty space I would like to remove is indicated in the text in red in the following diagram.
Thank you for your help - it is much appreciated!
I have attached the code to reproduce this plot.
i <- structure(list(wd = c(0, 112.5, 135, 180, 202.5, 22.5, 225, 247.5,
270, 292.5, 337.5, 45, 67.5, 90), co2 = c(389.82, 376.82, 386.06,
392.04, 392.55, 387.97, 391.45, 389.87, 390.12, 389.68, 391.39,
390.1, 386.89, 383.05), ci1 = c(388.37, 367.67, 378.98, 381.76,
388.63, 386.65, 388.32, 388.5, 389.03, 387.25, 389.05, 388.65,
385.64, 381.1), ci2 = c(391.26, 385.98, 393.15, 402.31, 396.46,
389.28, 394.58, 391.23, 391.21, 392.12, 393.73, 391.55, 388.15,
385.01)), row.names = c(NA, -14L), class = "data.frame")
library(ggplot2)
ggplot(data = i, aes(x = wd, y = co2)) +
geom_point(size=4, colour = "red")+
geom_linerange(aes(ymax =ci2, ymin=ci1), colour = "red", size = 2)+
coord_polar()+
geom_hline(yintercept = seq(365, 405, by = 5), colour = "grey", size = 0.2) +
geom_vline(xintercept = seq(0, 360, by = 22.5), colour = "grey", size = 0.2) +
scale_x_continuous(limits = c(0, 360), expand = c(0, 0),
breaks = seq(0, 359.99, by = 22.5),
labels=c("N","NNE","NE","ENE","E","ESE","SE","SSE",
"S","SSW","SW","WSW","W","WNW","NW","NNW"),position = "top") +
scale_y_continuous(limits = c(365, 405), breaks = seq(365, 405, by = 10)) +
theme_bw() +
theme(panel.border = element_blank(),
panel.grid = element_blank(),
legend.key = element_blank(),
axis.ticks = element_line(colour = "grey"),
axis.ticks.length = unit(-1, "lines"),
axis.ticks.margin = unit(1.3,"lines"),
axis.text = element_text(size=24),
axis.text.x = element_text(vjust = -10),
axis.text.y = element_text(size=24),
axis.title = element_blank(),
axis.line=element_line(),
axis.line.x=element_blank(),
axis.line.y = element_line(colour = "grey"),
plot.title = element_text(hjust = 0, size = 20))
This is pretty easy to do with coord_curvedpolar from geomtextpath. The vjust argument will work as expected, pushing or pulling the text away from or towards the center of the plot. Here is axis.text.x = element_text(vjust = 2)
library(ggplot2)
library(geomtextpath)
ggplot(data = i, aes(x = wd, y = co2)) +
geom_point(size=4, colour = "red")+
geom_linerange(aes(ymax =ci2, ymin=ci1), colour = "red", size = 2)+
coord_curvedpolar()+
geom_hline(yintercept = seq(365, 405, by = 5), colour = "grey", size = 0.2) +
geom_vline(xintercept = seq(0, 360, by = 22.5), colour = "grey", size = 0.2) +
scale_x_continuous(limits = c(0, 360), expand = c(0, 0),
breaks = seq(0, 359.99, by = 22.5),
labels=c("N","NNE","NE","ENE","E","ESE","SE","SSE",
"S","SSW","SW","WSW","W","WNW","NW","NNW"),position = "top") +
scale_y_continuous(limits = c(365, 405), breaks = seq(365, 405, by = 10)) +
theme_bw() +
theme(panel.border = element_blank(),
panel.grid = element_blank(),
legend.key = element_blank(),
axis.ticks = element_line(colour = "grey"),
axis.ticks.length = unit(-1, "lines"),
axis.text = element_text(size = 12),
axis.text.x = element_text(vjust = 2),
axis.text.y = element_text(size = 12),
axis.title = element_blank(),
axis.line=element_line(),
axis.line.x=element_blank(),
axis.line.y = element_line(colour = "grey"),
plot.title = element_text(hjust = 0, size = 20))
The same plot with axis.text.x = element_text(vjust = 5)
The same plot with axis.text.x = element_text(vjust = -1)

Extent Viridis color scheme

Is there a way i could extent (prepend) the value 'transparent' at the start of the Viridis colour scheme? Or maybe to overrule it in a way that every value (let's say) below -30 is the 'colour' transparent?
plot.nme = paste0('PLOTS/','temphi_tomorrow_test.png')
pred <- ggplot() +
geom_raster(data = nnmsk_df , aes(x = x, y = y, fill = var1.pred),interpolate = FALSE) +
annotate(geom="raster", x=ctry$x, y=ctry$y, alpha=.2,fill = scales::colour_ramp(c("#00000000","grey"))(ctry[,3])) +
theme_void() + # Empty theme without axis lines and texts
scale_fill_viridis(option = "viridis", direction = 1,name="Maximum temperature (°C)", limits = c(-30,30),breaks=c(-30,-25,-20,-15,-10,-5,0,5,10,15,20,25,30), na.value = "transparent") +
geom_text(aes(label = dfdat$temphi),x = dfdat$Longitude,y = dfdat$Latitude,size=0.6,col="#ffffff",
hjust = -0.01,
vjust = 0.01) +
geom_point(shape = 1)
pred_snow <- pred +
geom_contour(aes(x = x, y = y, z = var1.pred),data = nnmsk_df, na.rm = TRUE,bins = 6,colour = "white", alpha = 0.2,size=0.1) +
theme(
panel.background = element_rect(fill = "transparent", colour = NA),
plot.background = element_rect(fill = "transparent", colour = NA),
legend.background = element_rect(fill = "transparent", colour = NA),
legend.box.background = element_rect(fill = "transparent", colour = NA),
legend.position = c(0.5, 0.3),
legend.key.size = unit(0.4, "cm"),
legend.key.width = unit(0.4, "cm"),
legend.key.height = unit(0.1, "cm"),
legend.direction = "horizontal",
legend.title = element_text(color = "white", size = 4),
legend.text = element_text(colour="white",size=3)
)
pred_snow
ggsave(plot.nme, height = graph_height , width = graph_height * aspect_ratio,bg = "transparent",dpi = 300)

How to hide a single key in R?

Just to be clear: I am relatively new to R, and the code I am using is borrowed from someone else.
I have this graph for polling averages:
Here is my code: https://pastebin.com/qvQERRUH
library("tidyverse")
polls <- read.csv("polls_Paris.csv")
polls <- polls %>%
mutate(
date = format(as.Date(c(paste(year,month, day, sep="-")), by = "days"))
)
for(i in c("LFI", "PS", "EELV", "PP", "Griveaux", "LREM", "Villani", "Agir", "LR", "RN", "LP")) {
polls <- within(polls, {
assign(paste0("ci_", i), 1.96 * sqrt(( get(paste0("liste_", i)) * (100 - get(paste0("liste_", i)))) / n))
}
)
}
polls.10m <- polls[polls$date > seq(as.Date(Sys.Date()), length = 2, by = "-10 months")[2],]
polls.100 <- polls[order(as.Date(polls$date)),] %>% top_n(5000, as.Date(polls$date))
#Results = data.frame(date = as.Date("2019-12-01"), support = c(69.1,30.9))
svg('Opinion polling for the 2020 Paris municipal election.svg', width = 12, height = 6)
polls.100 %>%
gather(party, support, c(liste_LFI,liste_PS,liste_EELV,liste_PP,liste_Griveaux,liste_LREM,liste_Villani,liste_Agir,liste_LR,liste_RN,liste_LP), factor_key=TRUE) %>%
ggplot(aes(x=as.Date(date), y=support, colour=party)) +
geom_point(size=2.5, alpha=0.275) +
geom_smooth(se=FALSE, method="loess", span=1) +
labs(y = NULL,
x = NULL) +
guides(colour = guide_legend(ncol = 1, override.aes = list(linetype = 0, size = 3, alpha = 1))) +
scale_colour_manual(labels = c("Simonnet (LFI)", "Hidalgo (PS-PCF-G·s)", "Belliard (EELV)", "Gantzer (DVG)", "Griveaux (LREM-MR-UDI)", "Griveaux (avant diss. de Villani)", "Villani (Diss. LREM-PRG)", "Bournazel (Agir)", "Dati (LR)", "Federbusch (DVD-RN)", "Campion (SE)"), values = c("#cc2443", "#FF8080", "#00c000", "#ffc0c0", "#ffeb00", "#ffeb00", "#FF7F50", "#adc1fd", "#0066CC", "#0D378A", "#808080", "#808080")) +
theme(
plot.margin = margin(t = 0, unit = "cm"),
plot.background = element_blank(), panel.background = element_rect(fill = "grey92", colour = NA),
panel.border = element_blank(), legend.background = element_rect(fill = "transparent", colour = NA),
legend.key = element_rect(fill = "transparent", colour = NA), legend.title = element_blank(),
strip.background = element_rect(fill = "transparent", colour = NA),
panel.grid.major = element_line(colour = "#FFFFFF"), panel.grid.minor = element_line(colour = "#FFFFFF", size = 0.25),
axis.ticks = element_line(colour = "grey20"), axis.line = element_blank(),
plot.title = element_text(size = 12, hjust = 0),
plot.subtitle = element_text(size = 12, hjust = 0),
plot.caption = element_text(size = 12, colour = "#212121"),
axis.title = element_text(size = 12, face = "plain"), axis.text = element_text(size = 12, face = "plain", colour = "grey30"),
legend.position = "right",
legend.text = element_text(size = 12), strip.text = element_text(size = 12, face = "plain"),
legend.margin = margin(t = 0, unit = "cm"),
) +
scale_y_continuous(breaks = seq(0,33,5), minor_breaks = seq(0,33,1), limits = c(0, 33), expand = c(0, 0)) +
scale_x_date(breaks="6 months", minor_breaks="1 month", expand = c(0, 0))
#geom_point(data = Results, colour = c("#808080", "#E81B23"), size=4, shape=5) +
#geom_point(data = Results, colour = c("#808080", "#E81B23"), size=3.5, shape=18)
dev.off()
As you can see, Griveaux's line is split to separate the before-and-after of Villani's dissident candidacy; it's actually 2 separate lines (also separate in the dataset). Griveaux's name therefore has to appears twice.
How do I do to remove the key of a single set (remove the key for both the dots and regression line)?
Here is a hack. To remove a legend key, remove it from the breaks argument to scale_*_manual or equivalent but you must keep the same number of values as there are unique values in the color/fill aesthetic.
This is better shown with an example. I will use built-in data set iris.
To remove the legend key relative to "versicolor",
levels(df1$Species)
#[1] "setosa" "versicolor" "virginica"
just don't include it in the breaks.
library(ggplot2)
df1 <- iris[3:5]
ggplot(df1, aes(Petal.Length, Petal.Width, color = Species)) +
geom_point() +
geom_smooth(se = FALSE, method = "loess", span = 1) +
scale_color_manual(breaks = c("setosa", "virginica"),
values = c("red", "green", "blue"))

Adjusting space between legend text and boxes after coord_flip() in ggplot

I am trying to move the legend text and legend boxes further apart (horizontally) on a box and jitter plot. The complicating factor is the coord_flip I used to make the boxplot horizontal. In theme I tried using both legend.spacing.x and legend.spacing.y but neither had any effect on the distance between legend text and legend boxes.
Here is the graph with fake data. More complex than necessary I know but I need to be able to make it work with all the complications.
library(dplyr)
library(ggplot2)
set.seed(01234)
# make some data
totDays <- data.frame(id = 1:80,
group = rep(c("Placebo", "Drug"), each = 40),
total84 = c(pmin(abs(round(rnorm(40, 55, 30))),84), pmin(abs(round(rnorm(40, 38, 30))),84)))
# get some descriptives
(groupDF <- totDays %>% group_by(group) %>%
dplyr::summarise(m = mean(total84, na.rm = T),
sd = sd(total84, na.rm = T),
count = n()) %>%
mutate(se = sd/sqrt(count)))
# now for the box and scatter plot
(g <- ggplot(totDays, aes(group, total84, colour = group)) +
geom_jitter(size = 1, width = 0.1) + # so points aren't overlaid, width controls how much jitter
geom_point(stat = "summary", fun.y = "mean", shape = 3, size = 3, colour = "black") + # crosses for mean
geom_boxplot(alpha = 0, width = 0.5, lwd = 1, size = 0.5) +
scale_color_manual(values = c("#00AFBB", "#E7B800")) +
scale_y_continuous(breaks = seq(0,84,14), minor_breaks = seq(0, 84, 14)) + # changes minor break line
coord_flip() +
labs(y = "Score") +
geom_hline(yintercept = c(groupDF$m), linetype = "dotted") +
geom_segment(x = 2.38, xend = 2.38, y = groupDF$m[2] + .1, yend = groupDF$m[1] - .1, size = .7, arrow = arrow(end = "both", type = "open", length = unit(0.15, "cm")), colour = "#696969") +
annotate("text", x = 2.46, y = mean(groupDF$m), label = paste0("italic(p) == ", 0.02), parse = T) +
theme_bw() +
theme(axis.title.y = element_blank(),
axis.ticks.y = element_blank(),
axis.text.y = element_blank(),
axis.text.x = element_text(size = 13),
axis.title.x = element_text(size = 13, face = "bold", margin = margin(t = 0, r = 0, b = 10, l = 0), vjust = -2), # note the use of margin to move the title away from the axis text
legend.title = element_blank(),
legend.position = "top",
legend.spacing.y = unit(.1, "cm"),
legend.box.spacing = unit(.1, "cm"), # adjusts distance of box from x-axis
legend.key.size = unit(1, "cm"),
legend.text = element_text(size = 13, face = "bold"),
strip.text = element_text(size = 13, face = "bold"),
panel.grid.major.y = element_blank(),
panel.grid.major.x = element_line(size=.4, color="#F7F7F7")))
Use either stringr::str_pad() or theme(legend.spacing.x = ...) or both
g <- ggplot(totDays, aes(group, total84, colour = group)) +
geom_jitter(size = 1, width = 0.1) + # so points aren't overlaid, width controls how much jitter
geom_point(stat = "summary", fun.y = "mean", shape = 3, size = 3, colour = "black") + # crosses for mean
geom_boxplot(alpha = 0, width = 0.5, lwd = 1, size = 0.5) +
scale_color_manual(values = c("#00AFBB", "#E7B800"),
### added
labels = stringr::str_pad(c("Drug", "Placebo"), 10, "right")) +
scale_y_continuous(breaks = seq(0,84,14), minor_breaks = seq(0, 84, 14)) + # changes minor break line
coord_flip() +
labs(y = "Score") +
geom_hline(yintercept = c(groupDF$m), linetype = "dotted") +
geom_segment(x = 2.38, xend = 2.38, y = groupDF$m[2] + .1, yend = groupDF$m[1] - .1, size = .7,
arrow = arrow(end = "both", type = "open", length = unit(0.15, "cm")), colour = "#696969") +
annotate("text", x = 2.46, y = mean(groupDF$m), label = paste0("italic(p) == ", 0.02), parse = T) +
theme_bw() +
theme(axis.title.y = element_blank(),
axis.ticks.y = element_blank(),
axis.text.y = element_blank(),
axis.text.x = element_text(size = 13),
axis.title.x = element_text(size = 13, face = "bold",
margin = margin(t = 0, r = 0, b = 10, l = 0), vjust = -2),
legend.title = element_blank(),
legend.position = "top",
### added
legend.spacing.x = unit(0.25, 'cm'),
legend.spacing.y = unit(.1, "cm"),
legend.box.spacing = unit(.1, "cm"), # adjusts distance of box from x-axis
legend.key.size = unit(1, "cm"),
legend.text = element_text(size = 13, face = "bold"),
strip.text = element_text(size = 13, face = "bold"),
panel.grid.major.y = element_blank(),
panel.grid.major.x = element_line(size=.4, color="#F7F7F7"))
Created on 2019-03-11 by the reprex package (v0.2.1.9000)

Resources