所以我有一堆研究,我想繪制從所有研究中獲得的回歸線。
我有一組斜率和截距值,以及每條線的 x 限制,但我需要分別設定每條線的 x 限制,因為它們都是不同的......
我已經絞盡腦汁好幾天了,但不知道如何使用 ggplot 來實作這一點,如果我可以給出一個xlim傳遞給斜率和截距值的值串列?
這是我的資料框的一個子集......
empirical_studies <- tibble(slope = c(-1.52, -1.42, -1.56, -1.57, -1.57, -1.68, -1.67, -1.6, -1.73, -1.69, -1.79), intercept = c(12.07, 11.29, 12.21, 12.26, 12.14, 12.5, 12.58, 12.28, 12.72, 12.53, 12.29), xmin = c(9.00, 6.00, 6.00, 6.00, 6.00, 9.00, 7.00, 7.00, 7.00, 7.00, 18.00), xmax = c(26.00 59.00, 53.00, 53.00, 53.00, 63.00, 67.00, 64.00, 64.00, 64.00, 50.00))
非常感謝任何幫助!
老實說,我并沒有真正嘗試太多,我知道我無法傳遞一組xlim值...我嘗試撰寫一個回圈(如下),但這似乎也不起作用:
plot = ggplot(empirical_studies, aes(x=empirical_studies$diameter_stem_average, y=empirical_studies$density))
for (i in 1:(length(empirical_studies)-1)){
plot=plot geom_abline(slope = empirical_studies$slope[i], intercept = empirical_studies$intercept[i])
xlim(empirical_studies$min_dq[i], empirical_studies$max_dq[i])
i <- i 1
}
print(plot)
uj5u.com熱心網友回復:
如果要繪制單獨的線段,可以使用geom_line()起點和終點。
由于您已經有了x最小值和最大值的值,您可以簡單地使用slopeandintercept來計算y這些點的值,然后繪制它。對于這些操作,您需要唯一標識每條曲線,因此我只是為每條曲線應用了一個數字,但您可以根據您的資料使用更多資訊命名。
我在下面顯示了兩個選項,具體取決于您是要過度繪制所有內容還是要為每個選項單獨繪制。對于 faceted 選項,您可以指定sacles = "free"讓每個 facet 單獨重新縮放軸。否則,它會選擇捕獲所有資料的最廣泛范圍。
library(tidyverse)
empirical_studies <- tibble(slope = c(-1.52, -1.42, -1.56, -1.57, -1.57, -1.68, -1.67, -1.6, -1.73, -1.69, -1.79),
intercept = c(12.07, 11.29, 12.21, 12.26, 12.14, 12.5, 12.58, 12.28, 12.72, 12.53, 12.29),
xmin = c(9.00, 6.00, 6.00, 6.00, 6.00, 9.00, 7.00, 7.00, 7.00, 7.00, 18.00),
xmax = c(26.00, 59.00, 53.00, 53.00, 53.00, 63.00, 67.00, 64.00, 64.00, 64.00, 50.00))
# generate list of start and end points for each line
d <- empirical_studies %>%
mutate(study_id = row_number()) %>%
mutate(across(starts_with("x"), ~ slope * . intercept, .names = "y{str_sub(.col, 2, 4)}")) %>%
pivot_longer(starts_with(c("x", "y"))) %>%
separate(name, into = c("var", "position"), sep = 1) %>%
pivot_wider(names_from = var)
d
#> # A tibble: 22 × 6
#> slope intercept study_id position x y
#> <dbl> <dbl> <int> <chr> <dbl> <dbl>
#> 1 -1.52 12.1 1 min 9 -1.61
#> 2 -1.52 12.1 1 max 26 -27.4
#> 3 -1.42 11.3 2 min 6 2.77
#> 4 -1.42 11.3 2 max 59 -72.5
#> 5 -1.56 12.2 3 min 6 2.85
#> 6 -1.56 12.2 3 max 53 -70.5
#> 7 -1.57 12.3 4 min 6 2.84
#> 8 -1.57 12.3 4 max 53 -71.0
#> 9 -1.57 12.1 5 min 6 2.72
#> 10 -1.57 12.1 5 max 53 -71.1
#> # … with 12 more rows
# plotted together
d %>%
ggplot(aes(x, y))
geom_line(aes(color = factor(study_id)))

# plotted separately
d %>%
ggplot(aes(x, y))
geom_line()
facet_wrap(~study_id) # can add scales = "free" to scale axes separately

使用reprex v2.0.2創建于 2022-11-09
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/531113.html
標籤:rggplot2
上一篇:修改ggplots的顯示順序
