ggplot(irrigation_data, aes(x = Temperature)) +
geom_histogram(aes(y = after_stat(density)), binwidth = 2, fill = "lightblue") +
geom_density(color = "blue", size = 1) +
labs(title = "Soil Temperature Distribution",
x = "Temperature (°C)",
y = "Density") +
theme_minimal()
这是我希望我的直方图/密度图的外观:
可复制的示例:
library(ggplot2)
set.seed(101)
dd <- data.frame(Temperature = runif(1000, min = 0, max = 45))
ggplot(dd, aes(x = Temperature)) +
geom_histogram(aes(y = after_stat(density)), binwidth = 2) +
geom_density()
通常,我们将内核密度估计限制为某些界限。使用
density
我们可以通过设置
from=
和
to=
> hist(x, freq=FALSE, col='skyblue', border='skyblue')
>
> density(x) |> lines(col='blue', lty=2)
> density(x, from=0, to=max(x)) |> lines(col='red')
>
> legend('bottom', col=c('blue', 'red'), lty=2:1, leg=c('normal', 'constrained'))
您可以从[0,y]开始,但是如果有零值接近零,[0,0]可能是没有意义的。
data:
set.seed(42)
x <- runif(1e4, 0, 45)
为了确保直方图以零开始启动,请使用
boundary = 0
library(ggplot2)
set.seed(101)
dd <- data.frame(Temperature = runif(1000, min = 0, max = 45))
ggplot(dd, aes(x = Temperature)) +
geom_histogram(aes(y = after_stat(density), fill = "Histogram"), binwidth = 2, boundary = 0, breaks = seq(0, max(dd$Temperature)+1)) +
geom_density(aes(color = "Density"), size = 1, y= "Density",bounds=c(0, max(dd$Temperature))) +
labs(title = "Soil Temperature Distribution",
y = "Density") +
theme(
panel.grid = element_blank(),
plot.title = element_text(hjust = 0.5),
legend.position = "bottom",
axis.line = element_line(),
panel.background = element_rect(fill="white"),
panel.border = element_rect(colour = "black", fill=NA, linewidth=1)
) +
scale_fill_manual(values = "#9FC0DC") +
scale_color_manual(values = "#3A73AF") +
guides(fill = guide_legend(title = NULL), color = guide_legend(title = NULL))