I have the following two dataframes
df <- data.frame(Groesse=c("A", "B", "C", "D"),
x=c(0, 1, 30, 25),
y=c(0, 90, 85, 20))
df_text <- data.frame(Groesse=c("X", "Y"),
x=c(1, 30),
y=c(105, 105))
and tried to achieve what I want with the following:
plot <- ggplot(df)
geom_point(aes(x, y))
geom_text(data = df_text, aes(x, y, label = "Groesse"))
scale_y_continuous(limits = c(0,100), expand = c(0,0))
coord_cartesian(clip = "off")
theme(plot.margin = unit(c(10, 1, 1, 1), "lines"))
plot
I would like to have the annotations (using geom_text()
) to be above the scatterplot, but outside of the plot area. However, my plot is missing the values from geom_text()
.
Desired output (just a sketch):
Any idea how I can add the text outside the plot area without producing two different plots and then combining those in a grid?
CodePudding user response:
In addition to turning clipping off in the co-ordinates function, you need to set the out-of-bounds oob
argument in scale_y_continuous()
so the data isn't censored.
ggplot(df)
geom_point(aes(x, y))
geom_text(data = df_text, aes(x, y, label = "Groesse"))
scale_y_continuous(limits = c(0,100), expand = c(0,0), oob = ~ .x)
coord_cartesian(clip = "off")
theme(plot.margin = unit(c(10, 1, 1, 1), "lines"))
CodePudding user response:
This is just to point out an alternative to using geom_text()
for annotations. For continuous axes, you can use the secondary axis to add some annotations.
library(ggplot2)
df <- data.frame(Groesse=c("A", "B", "C", "D"),
x=c(0, 1, 30, 25),
y=c(0, 90, 85, 20))
df_text <- data.frame(Groesse=c("X", "Y"),
x=c(1, 30),
y=c(105, 105))
ggplot(df)
geom_point(aes(x, y))
scale_y_continuous(
limits = c(0,100), expand = c(0,0)
)
scale_x_continuous(
sec.axis = sec_axis(
~.x, name = NULL, breaks = c(1, 30),
labels = rep("Groesse", 2)
)
)
theme(
axis.ticks.length.x.top = unit(0, "pt"),
axis.text.x.top = element_text(margin = margin(b = 10))
)