如何使我的密度图从y = 0开始? 我希望该行从y = 0开始。 这是我使用的代码: ggplot(inrigation_data,aes(x =温度)) + geom_histogram(aes(y = after_stat(密度)),binwidth = 2,fill =“ lightblue&qu ...

问题描述 投票:0回答:2

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()

这是我希望我的直方图/密度图的外观:Results of my code

可复制的示例:

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()

My desired output 通常,我们将内核密度估计限制为某些界限。使用

density

我们可以通过设置

from=
to=
r ggplot2
2个回答
3
投票
> 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)

enter image description here为了确保直方图以零开始启动,请使用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))

2
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.