Move only some x axis labels down in ggplot - r

See this plot:
tibble(x = 0:10, y = rnorm(11)) %>%
ggplot(aes(x,y)) +
geom_point() +
scale_x_continuous(breaks = c(seq(0,10,2)/10, seq(2,10,1)))
The labels in the beginning of the axis are very crowded. Is there a way to push down only some labels (e.g. those of c(0.2, 0.6, 0.8)) so that all labels would be readable? Bonus: add a vertical line from ticks to those labels which have been pushed down (in other words make the tick longer).
I know I can use vjust = -5 as in + theme(axis.text.x = element_text(vjust = -5)) but that would push down all labels.

Here is a very simple method that pushes down the axis text by adding a new line character \n before the label in the vector x_ticks.
library(tidyverse)
x_ticks <- c(seq(0,10,2)/10, seq(2,10,1))
tibble(x = 0:10, y = rnorm(11)) %>%
ggplot(aes(x,y)) +
geom_point() +
scale_x_continuous(breaks = x_ticks,
labels = ifelse(x_ticks %in% c(0.2, 0.6, 0.8),
paste0("\n", x_ticks), x_ticks))
Created on 2022-03-30 by the reprex package (v2.0.1)

This is how to do it the hard way, if you really want those long ticks
tibble(x = 0:10, y = rnorm(11)) %>%
ggplot(aes(x,y)) +
geom_vline(xintercept = seq(2, 10, 4)/10, color = "white", size = 0.5) +
geom_point() +
scale_x_continuous(breaks = c(seq(0,10,4)/10, seq(2,10,1))) +
coord_cartesian(clip = "off", ylim = c(-2, 2)) +
annotate("text", label = format(seq(2, 10, 4)/10, nsmall = 1),
x = seq(2, 10, 4)/10, y = -2.4,
size = 3) +
annotate("segment", x = seq(2, 10, 4)/10, xend = seq(2, 10, 4)/10,
y = -2.33, yend = -2.2, size = 0.2) +
theme(axis.text = element_text(color = "black"))

Related

How to resolve problem with ggplot and ggsignif

I am trying to plot the differences in pairs. I found an example on this forum, but to this graph I would like to add the significance level information using the geom_signif function.
Unfortunately, I get the message back:
"Error in f (...):
Can only handle data with groups that are plotted on the x-axis "
Can someone help me fix this problem?
d <- data.frame(y = rnorm(20, 9, 2),
group = as.factor(rep(c('Post-FAP', 'Post-DEP'), each = 10)),
id = rep(1:10, 2))
ggplot(d, aes(y = y)) +
geom_boxplot(aes(x = rep(c(-2.5, 2.5), each = 10), group = group), fill = '#47E3FF') +
geom_point(aes(x = rep(c(-1, 1), each = 10)), shape = 21, size = 1.5, col = "black", fill = "grey") +
geom_line(aes(x = rep(c(-1, 1), each = 10), group = id)) +
#geom_signif(annotation = "p=0.05", y_position = 13, xmin = -2.5, xmax = 2.5, tip_length = .02) +
scale_x_continuous(breaks = c(-2.5, 2.5), labels = c("Post-FAP", "Post-DEP")) +
scale_y_continuous(minor_breaks = seq(5, 14, by =1),
breaks = seq(6, 14, by = 2), limits = c(5, 14),
guide = "axis_minor") +
theme_bw() +
theme(legend.position = "none", panel.grid = element_blank())
I think what you need to do is install ggh4x. It is an addon to ggplot2 that has some helpful tools, like properly adding ticks and minor ticks in your case. Once you load the R package then you should be good to go.
Edit:
The reason that you were getting that error was that you were not specifying group() for ggsignif
library(ggh4x)
library(ggplot2)
library(ggsignif)
ggplot(d, aes(y = y)) +
geom_boxplot(aes(x = rep(c(-2.5, 2.5), each = 10), group = group), fill = '#47E3FF') +
geom_point(aes(x = rep(c(-1, 1), each = 10)), shape = 21, size = 1.5, col = "black", fill = "grey") +
geom_line(aes(x = rep(c(-1, 1), each = 10), group = id)) +
geom_signif(d, mapping = aes(x=id, y=y,group=group),annotation = "p=0.05", y_position = 13, xmin = -2.5, xmax = 2.5, tip_length = .02) +
scale_x_continuous(breaks = c(-2.5, 2.5), labels = c("Post-FAP", "Post-DEP")) +
scale_y_continuous(minor_breaks = seq(5, 14, by =1),
breaks = seq(5, 14, by = 2), limits = c(5, 14),
guide = "axis_minor") +
theme_bw() +
theme(legend.position = "none", panel.grid = element_blank())
There is a thread here on the error message you posted, saying that all the information on aes (x and y) need to be accessible by the subfunction, i.e. geom_signif.
Using ggplot(d, x=aes(as.numeric(group), y=y, group = group)) worked for me.
Interestingly, ggplot(d, x=aes(rep(c(-2.5, 2.5), each = 10), y=y, group = group)) , did not return an error, but also did not show the geom_signif annotation.

Annotate ggplot2 across both axis: text keeps changing position

I am trying to annotate both axes of my plot with some text, but when I do that, I am unable to position the text as I would like. By adding new text on one axis, the text on the other axis gets misplaced.
How to deal with that?
Here is an example to illustrate my issue:
set.seed(1234)
x <- rnorm(50, 5, 2)
y <- x + 1 + rnorm(50)
data <- cbind.data.frame(x,y)
#Create a plot in which I annotate in one axis (it works great)
plot <- ggplot(data = data, aes(x, y))+
geom_point() +
geom_hline(yintercept=median(data$x, na.rm = T), color = 'red') +
geom_vline(xintercept=median(data$y, na.rm = T), color = 'red') +
labs(y="Label y", x = "Label x") +
geom_smooth(method=lm, na.rm = TRUE, fullrange= TRUE,
aes(group=1),colour="black") +
theme_bw() +
theme(axis.title.y = element_text(margin = margin(t = 0, r = 30, b = 0, l = 0))) +
theme(axis.title.x = element_text(margin = margin(t = 30, r = 0, b = 0, l = 0))) +
annotate("text", x = 9, y = -3, label = "Helpful Text2") +
annotate("text", x = 0.5, y = -3, label = "Helpful Text1") +
coord_cartesian(ylim = c(0, 15), clip = "off")
#Trying to add annotation to the second axis (it alters the axis of the plot, thereby misplacing the annotation I have done prior)
plot + annotate("text", x = 0, y = 8.5, label = "Helpful Text3", angle = 90) +
annotate("text", x = 0, y = 2, label = "Helpful Text4", angle = 90) +
coord_cartesian(xlim = c(1, 9), clip = "off")
Ideas?
You could try:
plot + annotate("text", x = -1, y = 14, label = "Helpful Text3", angle = 90) +
annotate("text", x = -1, y = 0, label = "Helpful Text4", angle = 90) +
coord_cartesian(ylim = c(0, 15), xlim = c(0, 10), clip = "off")
Just make sure you set fullrange = FALSE in geom_smooth when defining your plot.

Adding different geom_segment to every facet

I have the code below, and it works fine. The problem is, I would like to add "k" and plot a straight line similar to "z", but "k" is a vector of different numbers. Each element in "k" should be plotted as a line on the 3 facets created. If k was a singular value, I would just repeat the geom_segment() command with different y limits. Is there an easy way to do this? The final output should look like attached, assuming I could draw straight lines.
x <- iris[-1:-3]
bw <- 1
nbin <- 100
y <- head(iris, 50)[2]
z <- 1
k <- c(2, 3, 4)
ggplot(x, aes(x = Petal.Width)) +
geom_density(aes(y = bw *..count.., fill = Species), size = 1, alpha = 0.4) +
geom_segment(aes(x = 5, y = 250, xend = z, yend = 250, color = "red")) +
facet_wrap(~Species)+
scale_x_continuous(labels = scales::math_format(10^.x), limits = c(0, 5), expand = c(0,0)) +
scale_y_continuous(expand = c(0,0), limits = c(0, NA)) +
annotation_logticks(sides = "b", short=unit(-1,"mm"), mid=unit(-2,"mm"), long=unit(-3,"mm")) +
coord_cartesian(clip='off') + theme(panel.background = element_blank(),
panel.border = element_rect(colour = "black", fill=NA))
you can try this. Assuming that your plot is saved as p1.
k_data = data.frame(k, Species = levels(x$Species))
p1 + geom_segment(data = k_data, aes(x =5, y = 200, xend = k, yend = 200),
color = "blue", inherit.aes = F)
The idea is to create a dataframe with the columns k and Species and use this data exclusivley in a geom by setting inherit.aes = F
In this solution, the value of k is made part of the data set being plotted through a pipe. It is a temporary modification of the data set, since it is not assigned back to it nor to any other data set.
library(ggplot2)
library(dplyr)
x <- iris[-1:-3]
str(x)
bw <- 1
nbin <- 100
y <- head(iris, 50)[2]
z <- 1
k <- c(2, 3, 4)
x %>%
mutate(k = rep(k, each = 50)) %>%
ggplot(aes(x = Petal.Width)) +
geom_density(aes(y = bw *..count.., fill = Species), size = 1, alpha = 0.4) +
geom_segment(aes(x = 5, y = 250, xend = z, yend = 250), color = "red") +
geom_segment(aes(x = 5, y = 200, xend = k, yend = 200), color = "blue") +
facet_wrap(~Species)+
scale_x_continuous(labels = scales::math_format(10^.x), limits = c(0, 5), expand = c(0,0)) +
scale_y_continuous(expand = c(0,0), limits = c(0, NA)) +
annotation_logticks(sides = "b", short=unit(-1,"mm"), mid=unit(-2,"mm"), long=unit(-3,"mm")) +
coord_cartesian(clip='off') +
theme(panel.background = element_blank(),
panel.border = element_rect(colour = "black", fill=NA))

How to add common line and text as second x-axis label

I want to plot a graph. Several of my x-axis labels have a common label. So I want to add common text as label instead of several separate labels on x-axis as shown in the attached images. How can this be done?
library(dplyr)
library(forcats)
library(ggplot2)
df <- data.frame(conc = c(0, 10, 50, 100, "Positive Control"),
values = c(3, 3, 4, 5, 10),
name = c("TiO2 NP", "TiO2 NP", "TiO2 NP", "TiO2 NP", "Cyclophosamide"))
df$conc <- as.factor(df$conc)
labels2 <- paste0(df$conc, "\n", df$name)
df %>%
mutate(conc = fct_reorder(conc, values)) %>%
ggplot(aes(x = conc, y=values, fill = conc))+
geom_bar(stat = "identity",show.legend = FALSE, width = 0.6)+
scale_x_discrete(labels = labels2)+
labs(x = "\n Dose (mg/kg BW)")
I don't think there's a simple way. You have to play with ggplot2 for some time to make something really custom. Here's my example:
df %>%
mutate(
conc = fct_reorder(conc, values),
labels2 = if_else(
name == 'TiO2 NP',
as.character(conc),
paste0(conc, '\n', name)
)
) %>%
ggplot(aes(x=conc, y=values, fill = conc)) +
geom_bar(
stat = "identity",
show.legend = FALSE,
width = 0.6
) +
geom_rect(aes(
xmin = .4,
xmax = 5.6,
ymin = -Inf,
ymax = 0
),
fill = 'white'
) +
geom_text(aes(
y = -.4,
label = labels2
),
vjust = 1,
size = 3.4,
color = rgb(.3, .3, .3)
) +
geom_line(data = tibble(
x = c(.9, 4.1),
y = c(-1.2, -1.2)
),
aes(
x = x,
y = y
),
color = rgb(.3, .3, .3),
inherit.aes = FALSE
) +
geom_curve(data = tibble(
x1 = c(.8, 4.1),
x2 = c(.9, 4.2),
y1 = c(-.8, -1.2),
y2 = c(-1.2, -.8)
),
aes(
x = x1,
y = y1,
xend = x2,
yend = y2
),
color = rgb(.3, .3, .3),
inherit.aes = FALSE
) +
geom_text(aes(
x = 2.5,
y = -1.7,
label = 'TiO2 NP'
),
size = 3.4,
color = rgb(.3, .3, .3),
check_overlap = TRUE
) +
geom_text(aes(
x = 3,
y = -2.4,
label = '\n Dose (mg/kg BW)'
),
show.legend = FALSE,
check_overlap = TRUE
) +
theme_minimal() +
theme(
axis.text.x = element_blank(),
axis.title.x = element_blank()
) +
scale_y_continuous(
breaks = seq(0, 10, 2.5),
limits = c(-2.5, 10)
)
For a more automated approach, you can try placing the common variable in facet_grid with scales = "free", space = "free", to simulate a 2nd x-axis line. The rest of the code below are for aesthetic tweaks:
df %>%
mutate(conc = fct_reorder(conc, values)) %>%
ggplot(aes(x = conc, y = values, fill = conc)) +
geom_col(show.legend = F, width = 0.6) + #geom_col() is equivalent to geom_bar(stat = "identity")
facet_grid(~ fct_rev(name),
scales = "free", space = "free",
switch = "x") + #brings the facet label positions from top (default) to bottom
scale_x_discrete(expand = c(0, 0.5)) + #adjusts the horizontal space at the ends of each facet
labs(x = "\n Dose (mg/kg BW)") +
theme(axis.line.x = element_line(arrow = arrow(ends = "both")), #show line (with arrow ends) to
#indicate facet label's extent
panel.spacing = unit(0, "cm"), #adjusts space between the facets
strip.placement = "outside", #positions facet labels below x-axis labels
strip.background = element_blank()) #transparent background for facet labels

Applying log scale to y-axis for visualizing proportions with ggplot2

I am attempting to recreate some plots from a research article in R and am running into an issue with applying a log scale to y axis. The visualization I'm attempting to recreate is this:
reference plot with y log scale
I currently have a working version without the logarithmic scale applied to the y-axis:
Proportion_Mean_Plot <- ggplot(proportions, aes(days2,
proportion_mean, group = observation)) +
geom_point(aes(shape = observation)) +
geom_line() +
scale_x_continuous(breaks = seq(0,335,20)) +
scale_y_continuous(breaks = seq(0,6,.5)) +
theme_tufte() +
geom_rangeframe() +
theme(legend.position="none") +
theme(axis.line.x = element_line(colour = "black", size = 0.5, linetype = 1),
axis.line.y = element_line(colour = "black", size = 0.5, linetype = 1)) +
labs(title = "Proportion of Baseline Mean",
subtitle = "Daily steps within each intervention phase",
x = "DAYS",
y = "PROPORTION OF BASELINE \n(MEAN)") +
geom_vline(xintercept = 164.5) +
geom_hline(yintercept = 1) +
annotate("text", x = c(82, 246), y = 5,
label = c("Intervention 1", "Intervention 2")) +
geom_segment(aes(x = 0, y = mean, xend = end, yend = mean),
data = proportion_intervention1_data) +
geom_segment(aes(x = start, y = mean, xend = end, yend = mean),
data = proportion_intervention2_data, linetype = 4)
This produces a decent representation of the original:
normally scaled y-axis plot
I would like to try to apply that logarithmic scaling to more closely match it. Any help is appreciated.
As per Richard's suggestion, here is a quick example how you can use scale_y_log10:
suppressPackageStartupMessages(library(tidyverse))
set.seed(123)
# generate some data
proportions <- tibble(interv_1 = pmax(0.4, rnorm(160, mean = 1.3, sd = 0.2)),
interv_2 = pmax(0.01, rnorm(160, mean = 1.6, sd = 0.5)))
proportions <- proportions %>%
gather(key = observation, value = proportion_mean) %>%
mutate(days2 = 1:320)
# create the plot
ggplot(proportions, aes(days2, proportion_mean, group = observation)) +
geom_point(aes(shape = observation)) +
geom_line() +
scale_x_continuous(breaks = seq(0,335,20), expand = c(0, 0)) +
scale_y_log10(breaks = c( 0.1, 0.5, 1, 2, 3, 4, 5), limits = c(0.1, 5)) +
# theme_tufte() +
# geom_rangeframe() +
theme(legend.position="none") +
theme(axis.line.x = element_line(colour = "black", size = 0.5, linetype = 1),
axis.line.y = element_line(colour = "black", size = 0.5, linetype = 1)) +
labs(title = "Proportion of Baseline Mean",
subtitle = "Daily steps within each intervention phase",
x = "DAYS",
y = "PROPORTION OF BASELINE \n(MEAN)") +
geom_vline(xintercept = 164.5) +
geom_hline(yintercept = 1) +
annotate("text", x = c(82, 246), y = 5,
label = c("Intervention 1", "Intervention 2")) +
# plugged the values for the means of the two distributions
geom_segment(aes(x = 0, y = 1.3, xend = 164.5, yend = 1.3)) +
geom_segment(aes(x = 164.5, y = 1.6, xend = 320, yend = 1.6), linetype = 4)

Resources