@Chriss 给出了一个很好的解决方案——它确实在直方图的顶部生成了一条密度曲线;但是,它会更改 y 轴,因此您只能看到密度值(丢失计数值)。
这是另一种解决方案,它将频率计数放在左侧 y 轴上,并将密度添加为右侧 y 轴。根据需要调整代码,例如 bin、颜色等。我以 mtcars 数据为例,因为问题中没有提供要复制的代码或数据。除了这里使用的两个库(ggpubr 和 cowplot)之外,您可能还需要使用一些 ggplot 函数来更好地自定义这些绘图选项。
此解决方案的代码已从 https://www.datanovia.com/en/blog/ggplot-histogram-with-density-curve-in-r-using-secondary-y-axis/ 修改
# packages needed
library(ggpubr)
library(cowplot)
# load data (none provided in the original question)
data("mtcars")
# create histogram (I have 10 bins here, but you may need a different amount)
phist <- gghistogram(mtcars, x="hp", bins=10, fill="blue", ylab="Count (blue)") + ggtitle("Car Horsepower Histogram")
# create density plot, removing many plot elements
pdens <- ggdensity(mtcars, x="hp", col="red", size=2, alpha = 0, ylab="Density (red)") +
scale_y_continuous(expand = expansion(mult = c(0, 0.05)), position = "right") +
theme_half_open(11, rel_small = 1) +
rremove("x.axis")+
rremove("xlab") +
rremove("x.text") +
rremove("x.ticks") +
rremove("legend")
# overlay and display the plots
aligned_plots <- align_plots(phist, pdens, align="hv", axis="tblr")
ggdraw(aligned_plots[[1]]) + draw_plot(aligned_plots[[2]])