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")
Related
I'm working on a plot where I would like to change the axis thickness to match the boarder of the facet labels. Somehow axis.line = element_line(color="black", size=0.5) doesn't work - any ideas why?
This is my code...
ggplot(datgg_final, aes(y = total_GLS, x = timing)) +
geom_boxplot(aes(fill = genotype)) +
facet_grid(col=vars(genotype)) +
theme(legend.position = "none") +
scale_fill_manual(values=c("#0496FF", "#53A548")) +
ggtitle("Effect of Timing") +
xlab("Days since Defence Induction") +
ylab("Total Glucosinolates (µmol g^-1 DW)") +
theme(strip.background = element_rect(color = "black", fill ="white", size=0.5, linetype="solid"),
axis.line = element_line(color="black", size=0.5))
... and the plot:
enter image description here
Even in most basic plots I cannot change any axis settings (except the linetype), this code just shows the normal boxplot, no red axes, no change in line size:
ggplot(datgg_final, aes(y=total_GLS, x=timing)) +
geom_boxplot() +
theme(axis.line=element_line(size=0.5, color="red"))
Fortunately, this seems to be a simple clipping issue. Unfortunately, this can't be adressed with the normal ggplot interface (as far as I know), but you could mess around in the gtable to produce the plot you want.
Consider the following plot:
library(ggplot2)
library(grid)
g <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
geom_point() +
facet_grid(~ Species) +
theme(strip.background.x = element_rect(colour = "black", fill = "white",
size = 0.5, linetype = "solid"),
axis.line = element_line(colour = "black", size = 0.5))
g
You can see that the apparent linewidths of the facet strips and the axes are unequal. We can turn of the clipping by messing around in the gtable:
# Convert plot to gtable
gt <- ggplotGrob(g)
# Find the strips
is_strip <- grep("strip", gt$layout$name)
# Turn off clipping at highest level
gt$layout$clip[is_strip] <- "off"
# Turn off clipping at the strip level
gt$grobs[is_strip] <- lapply(gt$grobs[is_strip], function(strip) {
strip$layout$clip <- "off"
strip
})
# Plot
grid.newpage(); grid.draw(gt)
Now the apparent linewidths are the intended linewidths, but it took quite some extra steps to get there. If somebody has a more elegant solution, be welcome to post an alternative.
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"))
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)
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.
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)