【问题标题】:Density function ggplot2 deciding the scale_y_continuous scale factor决定 scale_y_continuous 比例因子的密度函数 ggplot2
【发布时间】:2020-06-02 22:31:39
【问题描述】:

所以我一直在尝试将我的 KDE 函数放入直方图,并且我设法做到了,但是当我尝试缩放 sec.axis = sec_axis(~./#number) 时,我似乎无法匹配它我的直方图有一种方法可以让它自动选择它应该显示的数字以获得最佳匹配。

我使用的代码是

a <- ggplot(birds, aes(birds$`Log10(Total Average)`))+
  geom_histogram(col = 'black', fill = 'white', binwidth = 0.2)+
  labs(x = 'Log10 total body mass (kg)', y = 'Frequency', title = 'Average total body mass (kg) of bird species (male adn female) in KNP')
a + geom_density(aes(y=..count..), col=2, size=1)+
  scale_y_continuous(sec.axis = sec_axis(~./40, name = "Density"))

【问题讨论】:

  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。

标签: r ggplot2 kernel-density


【解决方案1】:

与您之前的帖子一样,您没有提供数据集的可重现示例...因此很难提供适用于您的数据的解决方案。

一种方法是计算每个 bin 的最大计数和密度函数的最大值,然后您可以做出一个比率并将其应用于geom_density

set.seed(123)
df <- data.frame(Total_average = rnorm(100,0,2))
binwidth = 0.2

Seq <- seq(floor(min(df$Total_average)), ceiling(max(df$Total_average)), by = binwidth)

# Determine max count per bins
Max_HIST <- max(hist(df$Total_average, breaks = Seq)$counts)

# Determine the max of the density
Max_Dens <- max(density(df$Total_average)$y)

Ratio <- Max_HIST / Max_Dens

library(ggplot2)
ggplot(df, aes(Total_average))+
  geom_histogram(col = 'black', fill = 'white',binwidth = binwidth)+
  geom_density(aes(y = ..density..*Ratio))+
  scale_y_continuous(sec.axis = sec_axis(~./Ratio, name = "Density"))

它回答了你的问题吗?

如果没有,请按照本教程提供可重现的数据集示例:How to make a great R reproducible example


注意:由于某些原因,geom_histogramhist 函数似乎没有以完全相同的方式计算每个垃圾箱……目前,我对此没有很好的解释。

【讨论】:

    猜你喜欢
    • 2014-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    相关资源
    最近更新 更多