我正在嘗試繪制共享 y 軸的 4 個折線圖,但其中一個圖具有缺失值 (NA)。我希望能夠將 CI-TR 圖的 NA 值兩側的兩點連接起來。
這是我正在處理的資料(注意右側的 CI-TR 具有 NA 值)

這是我的代碼,我從excel檔案中讀取了表格:
#read the excel file (same as the table attached)
data <- read_csv("test3.csv", col_types = cols(.default = col_guess())
# gather the data for age and depth
plots <- data %>% filter(core_id == "BKM0817") %>%
gather(key = param, value = value, -core_id, -Age, -depth)
#this is to relabel the graph titles (NB the added a is to order alphabetically in the order I want them to appear)
plots %>%
mutate(facet_label = fct_recode(
param,
"delta ^ 13 * C[OM] ~(`\u2030 V-PDB`)" = "ad13com",
"delta ^ 15 * N ~(`\u2030 AIR`)" = "d15N",
"'C/N'" = "C/N",
"CI-TR" = "aaCI-TR"
)) %>%
# now plot the graphs
ggplot(aes(y = Age, x = value))
geom_hline(yintercept = c(10720, 10568, 10620), col = "black", alpha = 0.8, lty = 2)
geom_lineh(colour = "black", size = 0.5)
geom_point(size = 2)
facet_wrap(~facet_label, scales = "free_x", labeller = label_parsed, ncol = 4)
scale_y_reverse(# Features of the first axis
name = "Age (Cal. yrs BP)",
# Add a second axis and specify its features
sec.axis = sec_axis( trans=~./17.927, name="Depth (cm)")
)
labs(x = NULL, y = "Age (Cal. yrs BP)")
theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"))`
uj5u.com熱心網友回復:
如果有任何NA值,線 geom 只會切割,因此簡單的解決方案是NA從資料框中洗掉這些值。您可以使用na.omit()要做到這一點,但只要注意在那里你在你的代碼中使用它。您的原始資料集如下所示:
df <- data.frame(pos=1:4, A=c(1.05, 2.3, 4.24, 3.89),
B=c(4.44, NA, 2.22, 3.33))
df
>
pos A B
1 1 1.05 4.44
2 2 2.30 NA
3 3 4.24 2.22
4 4 3.89 3.33
收集后繪制此圖,您將得到:
df %>%
gather(key=type, value=value, -pos) %>%
ggplot(aes(x=pos, y=value))
geom_line(linetype=2, color='blue', size=0.7)
geom_point(color='red', size=3)
facet_wrap(~type)

如果您使用na.omit()on df,那么它將洗掉整個第二行,這也會洗掉列的第二個觀察值A。在這種情況下,只需確保在函式na.omit() 之后使用gather()以更長的時間旋轉資料框:
df %>%
gather(key=type, value=value, -pos) %>%
na.omit() %>% # important this comes after the gather
ggplot(aes(x=pos, y=value))
geom_line(linetype=2, color='blue', size=0.7)
geom_point(color='red', size=3)
facet_wrap(~type)

在你的情況下,下面的偽代碼讓你知道na.omit()在你自己的代碼中放置的位置:
plots %>%
mutate(...) %>%
na.omit() %>%
ggplot(...) ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315900.html
上一篇:嵌套ggplot直方圖而不是累積
下一篇:ggplot持續時間物件
