Enlarge ggplot2 legend - r

I have this plot made in R with ggplot2
which is drawn by the following code:
ggplot(mtcars) +
geom_smooth(fill='grey', alpha=0.3, span=0.1, aes(x=mpg, y=hp, color='AAA',linetype='AAA')) +
geom_smooth(fill='grey', alpha=0.3, span=0.9, aes(x=mpg, y=hp, color='BBB',linetype='BBB')) +
scale_colour_manual(name='test', values=c('AAA'='chocolate', 'BBB'='yellow')) +
scale_linetype_manual(name='test', values=c('AAA'='dashed','BBB'='solid')) +
theme_minimal() +theme(legend.position = "top")
Problem: from the legend, it is not easy to understand that the "AAA" line is dashed, since the box is too small.
How can I enlarge it?
I would love to have something similar to:

Try
# create your legend guide
myguide <- guide_legend(keywidth = unit(3, "cm"))
# now create your graph
ggplot(mtcars) +
geom_smooth(fill='grey', alpha=0.3, span=0.1,
aes(x=mpg, y=hp, color='AAA',linetype='AAA')) +
geom_smooth(fill='grey', alpha=0.3, span=0.9,
aes(x=mpg, y=hp, color='BBB',linetype='BBB')) +
scale_colour_manual(name='test',
values=c('AAA'='chocolate', 'BBB'='yellow'),
guide = myguide) +
scale_linetype_manual(name='test',
values=c('AAA'='dashed','BBB'='solid'),
guide = myguide) +
theme_minimal() + theme(legend.position = "top")
See ?guide_legend and here.
This will give you
You can use keywidth and keyheight to manipulate how much the key "stretches" into both directions. With title.position, direction, etc you can further finetune the legend.
Note that since you have multiple legends that are merged, you need to specify the guide to all merged scales. I simplified this by creating the guide outside as an object first.

Related

Edit distance between the facet / strip and the plot

For example,
library(ggplot2)
ggplot(mpg, aes(displ, cty)) + geom_point() + facet_grid(cols = vars(drv))
How can I change the distance between the strip and the main plot? (For example, create a gap between the strip and the main plot.)
But I don't need to change the strip size (different from this edit strip size ggplot2).
There can be multiple solutions to this problem.
geom_hline
A hacky one is to add a line (probably white, but it depends on your theme) on top of the plot. We can do this using geom_hline (or geom_vline if your facets are in rows). This creates an illusion of distance.
library(ggplot2)
ggplot(mpg, aes(displ, cty)) +
geom_point() +
facet_grid(cols = vars(drv)) +
# Add white line on top (Inf) of the plot (ie, betweem plot and facet)
geom_hline(yintercept = Inf, color = "white", size = 4) +
labs(title = "geom_hline")
strip.background
Another solution (as suggested by #atsyplenkov) is to use theme(strip.background = ...). There you can specify color of the border. However, this is not a perfect as it cuts border from all the directions (there might be a way to improve this).
ggplot(mpg, aes(displ, cty)) +
geom_point() +
facet_grid(cols = vars(drv)) +
# Increase size of the border
theme(strip.background = element_rect(color = "white", size = 3)) +
labs(title = "strip.background")
There is a much simpler solution
theme(strip.placement = "outside")

title font size in ggplot2 does not change

I know this is a very basic question, but I have trouble changing font size of axis labels in ggplot2. I used the code like below:
a <- ggplot(data1, aes(x=data2, y=data3)) +
geom_hline(yintercept=c(1, -1)) +
labs(x = data2, y = data3) +
theme_bw() +
theme(axis.text=element_text(size=10))
I tried to change the axis label size but they do not change.... Does anybody have suggestion?
Check out here how to alter labels in ggplot:
http://www.sthda.com/english/wiki/ggplot2-title-main-axis-and-legend-titles
In the example below we use axis.title to change the size, colour and face of the text.
library(ggplot2)
ggplot(mtcars, aes(x=mpg, y=disp)) +
geom_point() +
theme_bw() +
theme(axis.title=element_text(size=10, colour = "red", face = "bold"))

geom_label_repel text justification and alignment

Is there a possible work-around to left-justify the text label created by geom_label_repel (or geom_text_repel) in the example below where all text are placed with positive nudge_x value and y-only adjusted position in direction parameter? Currently, the default behavior is to center-align the text:
library(ggplot2)
library(ggrepel)
ggplot(mtcars, aes(x=factor(gear), y=mpg, colour=factor(gear))) +
geom_point(size=3) +
facet_wrap(~cyl, labeller=label_both) +
scale_x_discrete(expand=c(0, 1.5)) +
geom_label_repel(aes(label=rownames(mtcars)),
size=3, segment.size=0.25, nudge_x=0.5, direction="y")
I am looking to emulate the left-justification that is possible in geom_label (or geom_text) by setting hjust=0 as seen in example below, while being able to automatically repel labels in the y direction:
ggplot(mtcars, aes(x=factor(gear), y=mpg, colour=factor(gear))) +
geom_point(size=3) +
facet_wrap(~cyl, labeller=label_both) +
scale_x_discrete(expand=c(0, 1.5)) +
geom_label(aes(label=rownames(mtcars)), size=3, nudge_x=0.2, hjust=0)
Edited: As a hack, would it be possible to build hjust (and vjust) into ggrepel?
In the 4 years since OP posted this question, hjust= seems to have been added to the ggrepel package:
library(ggplot2)
library(ggrepel)
ggplot(mtcars, aes(x=factor(gear), y=mpg, colour=factor(gear))) +
geom_point(size=3) +
facet_wrap(~cyl, labeller=label_both) +
scale_x_discrete(expand=c(0, 1.5)) +
geom_label_repel(
aes(label=rownames(mtcars)), hjust=0,
size=3, segment.size=0.25, nudge_x=0.5, direction="y")

How to make gap between x and y axis and protruded ticks in ggplot2

How can I create the following style of graph:
Notice the gap between x-y axis (red circle) and protruded ticks in x-y axis (arrow).
At best I can do is this now:
library(ggplot2)
p <- ggplot(mpg, aes(class, hwy)) +
geom_boxplot() +
theme_bw(base_size=10)
p
One option is to remove the built-in axis lines and then use geom_segment to add axes with a gap. In order to make it easier to get the broken axis lines in the right place, we also use scale_y_continuous to specify exactly where we want the axis breaks and limits. The code also shows how to increase the size of the tick marks.
ggplot(data=mpg, aes(class, hwy)) +
geom_segment(y=10, yend=50, x=0.4, xend=0.4, lwd=0.5, colour="grey30", lineend="square") +
geom_segment(y=5, yend=5, x=1, xend=length(unique(mpg$class)),
lwd=0.5, colour="grey30", lineend="square") +
geom_boxplot() +
scale_y_continuous(breaks=seq(10,50,10), limits=c(5,50), expand=c(0,0)) +
theme_classic(base_size=12) +
theme(axis.line = element_blank(),
axis.ticks.length = unit(7,"pt"))
You can achieve something similar using ggthemes which provides geom_rangeframe and theme_tufte.
library(ggplot2)
library(ggthemes)
ggplot(mpg, aes(class, hwy)) +
geom_boxplot() +
geom_rangeframe() +
theme_tufte() +
theme(axis.ticks.length = unit(7, "pt"))
More inspiration here.
Originally posted as an answer to a related question, I was encouraged to share my answer here as well.
The ggh4x package has a truncated axis guide that solves this problem by taking advantage of position guide customisation introduced in ggplot2 v3.3.0. Because it uses the guide system directly instead of working through a geom, it is responsive to theme settings just as regular axes. (Disclaimer: I'm the author of ggh4x).
By default, it truncates the axis to the outermost breaks, but this can be adjusted.
library(ggplot2)
library(ggh4x)
ggplot(mpg, aes(class, hwy)) +
geom_boxplot() +
guides(x = "axis_truncated", y = "axis_truncated") +
theme(axis.line = element_line(colour = "black"))
Created on 2021-04-19 by the reprex package (v1.0.0)
The bars on the top and bottom of the lines are added with
geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.2)
or by adding geom to another layer.
stat_summary(fun.data = mean_sdl,
fun.args = list(mult = 1),
geom = "errorbar",
width = 0.1)

How can I separate x and y axis in ggplot2 [duplicate]

How can I create the following style of graph:
Notice the gap between x-y axis (red circle) and protruded ticks in x-y axis (arrow).
At best I can do is this now:
library(ggplot2)
p <- ggplot(mpg, aes(class, hwy)) +
geom_boxplot() +
theme_bw(base_size=10)
p
One option is to remove the built-in axis lines and then use geom_segment to add axes with a gap. In order to make it easier to get the broken axis lines in the right place, we also use scale_y_continuous to specify exactly where we want the axis breaks and limits. The code also shows how to increase the size of the tick marks.
ggplot(data=mpg, aes(class, hwy)) +
geom_segment(y=10, yend=50, x=0.4, xend=0.4, lwd=0.5, colour="grey30", lineend="square") +
geom_segment(y=5, yend=5, x=1, xend=length(unique(mpg$class)),
lwd=0.5, colour="grey30", lineend="square") +
geom_boxplot() +
scale_y_continuous(breaks=seq(10,50,10), limits=c(5,50), expand=c(0,0)) +
theme_classic(base_size=12) +
theme(axis.line = element_blank(),
axis.ticks.length = unit(7,"pt"))
You can achieve something similar using ggthemes which provides geom_rangeframe and theme_tufte.
library(ggplot2)
library(ggthemes)
ggplot(mpg, aes(class, hwy)) +
geom_boxplot() +
geom_rangeframe() +
theme_tufte() +
theme(axis.ticks.length = unit(7, "pt"))
More inspiration here.
Originally posted as an answer to a related question, I was encouraged to share my answer here as well.
The ggh4x package has a truncated axis guide that solves this problem by taking advantage of position guide customisation introduced in ggplot2 v3.3.0. Because it uses the guide system directly instead of working through a geom, it is responsive to theme settings just as regular axes. (Disclaimer: I'm the author of ggh4x).
By default, it truncates the axis to the outermost breaks, but this can be adjusted.
library(ggplot2)
library(ggh4x)
ggplot(mpg, aes(class, hwy)) +
geom_boxplot() +
guides(x = "axis_truncated", y = "axis_truncated") +
theme(axis.line = element_line(colour = "black"))
Created on 2021-04-19 by the reprex package (v1.0.0)
The bars on the top and bottom of the lines are added with
geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.2)
or by adding geom to another layer.
stat_summary(fun.data = mean_sdl,
fun.args = list(mult = 1),
geom = "errorbar",
width = 0.1)

Resources