【发布时间】:2022-06-11 19:27:12
【问题描述】:
我想使用 ggplot2 和 ggridges 将第二个 y 轴上的频率添加到脊线图
我找到了一个使用 geom_text (https://rdrr.io/cran/ggridges/man/stat_binline.html) 将频率添加为数字的教程,但是,我更愿意将它们添加为第二个 y 轴。
当然,我非常感谢 ggridges 之外的解决方案以获得类似的情节。
示例数据:
library(ggplot2)
library(ggridges)
library(lubridate)
# datapoints
data_timepoint <- data.frame(type=factor(c("A","B","C","D")),
start=as.Date(c("1990-01-01","2000-01-01","2010-01-01","2012-01-01")),
stop=as.Date(c(rep("2022-01-01",4))))
# frequencies
data_freq <- data.frame(type=c("A","A","B","C","D","D","D"),
year=ymd(year(as.Date(c("1991-01-01","1991-01-01","2005-01-01","2016-01-01","2013-01-01","2013-01-01","2015-01-01"))),truncated=2L))
# plot
ggplot(data_timepoint) +
geom_rect(aes(xmin=start, xmax=stop,
ymin=type, ymax=as.numeric(type)+0.9), fill="lightblue") +
geom_density_ridges(data=data_freq, aes(x=year,y=type),stat = "binline",
bins = 1, scale = 0.95, draw_baseline = FALSE, alpha=.5, binwidth=10,center=20) +
scale_x_date(date_breaks = "1 year",date_labels = "%Y") +
theme(axis.text.x = element_text(angle = 90),
axis.text.y = element_text(vjust = -2)) +
labs(title="",y="Type",x="Year")
由reprex package (v2.0.1) 于 2022-06-03 创建
【问题讨论】:
-
你的数据点太少了,我几乎看不出密度图的用处...... - 或者你有更多的数据点,你想分享更接近它的样本数据? (也许使用
?geom_density_ridges的例子? -
谢谢。是的,真实数据有更多的数据点。我认为样本数据应该很小,并且我使用的是长数据格式。因此,我给出了最能代表我的数据结构的示例数据。