I want to use a vertical and horizonal line to mark a point in a facetd plot.
But the vertical and horizonal line can not touch the axis boudary.
I used a simple example to show the problem.
library(tidyverse)
library(ggh4x)
# data prepared
df = data.frame(
x = c(1, 2, 3, 4, 10, 20, 30 ,40),
y = c(1, 2, 3, -1, 10 ,20, 30, -10),
group = c(1, 1, 1, 1, 2, 2, 2, 2)
)
add.point = data.frame(
group = c(1, 2),
x = c(1, 10),
y = c(1.5, 15),
x_hline = c(0, 0),
y_hline = c(1.5, 15),
x_vline = c(1, 10),
y_vline = c(0, 0)
)
I tried several ways, such as expand_limits()
, try scale_x(y)_continuous()
and coord_cartesian()
, but all failed.
By the way, I can live with the point y < 0
not showing up in the plot.
My question is that is there a way that make vertical and horizonal line touch the axis boudary in ggplot.
(p0 = df %>%
ggplot(aes(x = x, y = y)) +
geom_point() +
geom_smooth(se = F) +
facet_wrap(vars(group), scales = 'free')+
geom_point(data = add.point, aes(x = x, y = y), color = 'red')+
geom_segment(data = add.point,
aes(x = x_hline, y = y_hline,
xend = x, yend = y), linetype = 'dashed')+
geom_segment(data = add.point,
aes(x = x_vline, y = y_vline,
xend = x, yend = y), linetype = 'dashed'))
# try expand_limits()
(p1 = p0 + expand_limits(x = 0, y = 0))
# try scale_x(y)_continuous()
(p1 = p0 + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0)))
# try coord_cartesian()
(p1 = p0 + coord_cartesian(ylim = 0))
You could use eg -Inf
for the endpoints of your segments and use expand_limits
to extend the limits to zero:
library(ggplot2)
ggplot(df, aes(x = x, y = y)) +
geom_point() +
geom_smooth(se = F) +
facet_wrap(vars(group), scales = 'free')+
geom_point(data = add.point, aes(x = x, y = y), color = 'red')+
geom_segment(data = add.point,
aes(x = -Inf, y = y_hline,
xend = x, yend = y), linetype = 'dashed')+
geom_segment(data = add.point,
aes(x = x_vline, y = -Inf,
xend = x, yend = y), linetype = 'dashed') +
expand_limits(x = 0, y = 0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.