如何在ggplot中找到直方图的bin和binwidth的最佳值?

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

每次我使用ggplot建立直方图时,看起来都很难看。主要原因之一是我无法为直方图设置bin和binwidth的最佳值。我想知道R中是否有方法或功能可以帮助我找到最佳价值。为了便于讨论,下面是示例。

library(ggplot2)
library(tidyverse)
library(dplyr)
setwd("/Users/tingweima/Documents/R Practice")
df<-read_csv("store.csv")
#> Parsed with column specification:
#> cols(
#>   `Customer Name` = col_character(),
#>   Segment = col_character(),
#>   Country = col_character(),
#>   City = col_character(),
#>   State = col_character(),
#>   Region = col_character(),
#>   Category = col_character(),
#>   `Sub-Category` = col_character(),
#>   Sales = col_double(),
#>   Quantity = col_double(),
#>   Profit = col_double()
#> )
ggplot(df,aes(x=Profit))+geom_histogram()
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

enter image description here“利润”的范围介于-6599.978和8399.976之间,但此范围实际上未在此直方图中呈现。因此,我想知道如何在ggplot中找到直方图的bin和binwidth的最佳值,以使其更加清晰?在此先感谢您。

r ggplot2 histogram bin
1个回答
0
投票

我不确定“最佳”二进制宽度。那是很主观的。通常,获取日志可以帮助查看更多数据。但是在这种情况下,您会有许多负值(损失)。更好地了解损益的一种方法是将数据分为损益两类,然后使用利润的绝对值,但对这个新的损益变量进行分面,然后将x轴转换为对数刻度。

df %>%
  mutate(net=ifelse(Profit<0, "Loss", "Profit")) %>% 
  ggplot(aes(x=abs(Profit) + 0.001)) +  # + 0.001 in case there are 0s
  facet_grid(~net) +
  geom_histogram(aes(col=net)) +
  scale_x_log10(labels=function(x) sprintf("%.1f", x)) +
  xlab("Profit (dollars)")

enter image description here


或者,您可以指定较小的binwidth:

df %>%
  ggplot(aes(x=Profit)) + 
  geom_histogram(binwidth=30)

或使用功能。这是来自geom_histogram的帮助页面,该页面使用四分位数间距除以样本大小的立方根的两倍。这来自Freedman-Diaconis规则。

df %>%
  ggplot(aes(x=Profit)) + 
  geom_histogram(binwidth=function(x) 2 * IQR(x) / (length(x)^(1/3)))

enter image description here

但是那仍然不能真正说明这个故事。


数据

set.seed(1234)
df <- data.frame(Profit=rnorm(1000, 0, 6)^3)
© www.soinside.com 2019 - 2024. All rights reserved.