簡體   English   中英

如何在ggplot中使垂直和水平線與軸線邊界一致

[英]how to make vertical and horizonal line up to the axis boudary in ggplot

我想使用垂直和水平線來標記構面圖中的一個點。

但縱橫線不能觸及軸線邊界。

我用一個簡單的例子來說明問題。

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)
)

我嘗試了幾種方法,例如expand_limits()try scale_x(y)_continuous()coord_cartesian() ,但都失敗了。

順便說一句,我可以忍受y < 0沒有出現在情節中。

我的問題是,有沒有一種方法可以使垂直線和水平線接觸 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))

您可以使用例如-Inf作為段的端點,並使用expand_limits將限制擴展到零:

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)

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM