在想用某些值(例如:中值/平均值/等)繪制密度圖。我還想在繪圖區域上方顯示選定的值(例如中值),這樣它就不會干擾分布本身。此外,在現實生活中,我有更大、更多樣化的資料框(具有更多類別),因此我想傳播標簽,這樣它們就不會相互干擾(我希望它們具有可讀性和視覺效果)。
我在這里找到了類似的線索:
這是我想要的輸出(對不起質量,用油漆編輯):

此外,如果您更改“sample_name”的分組因子,那么您將看到更多“擁擠”的圖,與我的 irl 資料更相似。

uj5u.com熱心網友回復:
實作您想要的結果的一種選擇:
- 設定
clip="off" incoord_cartesian` - 通過增加標題的底部邊距為標簽留出一些空間
y=1.05為標簽設定(資料范圍的最大值 比例的默認擴展 0.05)- 放
min.segment.length=0 - 增加
ylim標簽 - 微調標簽的位置
注意:要獲得想要的結果,您可能需要擺弄微調、ylim 和邊距的值。
set.seed(123)
library(ggplot2)
library(ggrepel)
library(dplyr)
plot_distribution_with_values <- function(input_data,value_to_show="mean", grouping_factor = "group", title="", limit="") {
#determine the center values to be plotted as x intercepting line(s)
center_values = input_data %>% dplyr::group_by(!!rlang::sym(grouping_factor)) %>% dplyr::summarize(median_value = median(tail_length,na.rm = TRUE),mean_value=mean(tail_length,na.rm=T))
#main core of the plot
plot_distribution <- ggplot2::ggplot(input_data, aes_string(x=tail_length,color=grouping_factor))
geom_density(size=1, aes(y=..ndensity..)) theme_bw() scale_x_continuous(limits=c(0, as.numeric(limit)))
coord_cartesian(clip = "off", ylim = c(0, 1))
if (value_to_show=="median") {
center_value="median_value"
}
else if (value_to_show=="mean") {
center_value="mean_value"
}
#Plot settings (aesthetics, geoms, axes behavior etc.):
g.line <- ggplot2::geom_vline(data=center_values,aes(xintercept=!!rlang::sym(center_value),
color=!!rlang::sym(grouping_factor)),
linetype="longdash",show.legend = FALSE)
g.labs <- ggplot2::labs(title= "Tail lengths distribution",
x="tail length [units]",
y= "normalized density",
color=grouping_factor)
g.values <- ggrepel::geom_text_repel(data=center_values,
aes(x=round(!!rlang::sym(center_value)),
y = 1.05, color=!!rlang::sym(grouping_factor),
label=formatC(round(!!rlang::sym(center_value)),digits=1,format = "d")),
size=4, direction = "x", segment.size = 0.4,
min.segment.length = 0, nudge_y = .15, nudge_x = -10,
show.legend =F, hjust =0, xlim = c(0,200),
ylim = c(0, 1.15))
#Overall plotting configuration:
plot <- plot_distribution g.line g.labs g.values
theme(plot.title = element_text(margin = margin(b = 4 * 5.5)))
return(plot)
}
plot_distribution_with_values(tail_data, value_to_show = "median", grouping_factor = "group", title = "Tail plot", limit=200)

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/384677.html
