【问题标题】:How to minimize gaps on histogram in r如何最小化r中直方图的间隙
【发布时间】:2020-02-27 07:08:50
【问题描述】:

假设我有两种数据。一个在小范围内(从 0 到 0.5),另一个在大范围内(从 4 到 600)。第一个称为v,第二个称为mx

data<-structure(list(v = c(0.0741993337844943, 0.0469609897824665, 
0.27686789382899, 0.0899877689865293, 0.0533351613571831, 0.0949535942113873, 
0.132267448969788, 0.140736814439988, 0.170258755089611, 0.0012874981224646, 
0.0167425549755457), mx = c(20.2159112302004, 15.2656614271742, 
14.4361762323113, 8.87425807502441, 4.04997522826475, 34.9314254746675, 
45.699439750261, 16.0238858355385, 79.4436180395085, 598.247400459265, 
5.16677793308584)), class = "data.frame", row.names = c(NA, -11L
))

我使用这些代码进行绘图;

library(ggplot2)    
ggplot(data, aes(x=v)) + geom_histogram(bins=10)
ggplot(data, aes(x=mx)) + geom_histogram(bins=10)

例如。如您所见,v 图上没有介于 0.0 和 0.1 之间的值。我想为这个差距添加更多的值,例如 0.01、0.02...,而对于另一个情节,我想添加更多的值,例如 0-10-20-30...200-210

简而言之,我想最小化具有不同范围的所有图的所有间隙。

【问题讨论】:

  • 也许:ggplot(data, aes(x=v)) + geom_histogram(binwidth = 0.01) ?
  • 不确定您想要实现什么:您的data 根本不包含图表中存在差距的任何值 - 也许geom_density() 在视觉上更接近您想要实现的目标。跨度>

标签: r ggplot2 histogram


【解决方案1】:
data<-structure(list(v = c(0.0741993337844943, 0.0469609897824665, 0.27686789382899, 0.0899877689865293, 0.0533351613571831, 0.0949535942113873,  0.132267448969788, 0.140736814439988, 0.170258755089611, 0.0012874981224646, 0.0167425549755457),
                     mx = c(20.2159112302004, 15.2656614271742, 14.4361762323113, 8.87425807502441, 4.04997522826475, 34.9314254746675, 45.699439750261, 16.0238858355385, 79.4436180395085, 598.247400459265, 5.16677793308584)),
                class = "data.frame", row.names = c(NA, -11L))


library(ggplot2)    
ggplot(data, aes(x=data$v)) + geom_histogram(bins=10)
ggplot(data, aes(x=data$mx)) + geom_histogram(bins=10)

通过使用 bins 参数,您可以告诉 geom_histogram 制作 10 个“箱”,即将这些值分组到十个大小相等的 witdth range(x)/10 组中。

这意味着箱子的宽度现在是固定的(给定一个值范围)。

或者(但不是同时)我们可以告诉geom_histogram 使用给定的binwidth,即将值分组到给定宽度的组中。 现在bins的数量是range(x)/binwidth

应用于您的示例:

ggplot(data, aes(x=data$v)) + geom_histogram(binwidth=0.01)

ggplot(data, aes(x=data$mx)) + geom_histogram(binwidth=10)

【讨论】:

  • 您也可以在底部添加scale_x_log10() 以减少间隙,只是要注意这可能会使轴更难理解。
猜你喜欢
  • 1970-01-01
  • 2013-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-11
  • 1970-01-01
  • 1970-01-01
  • 2020-09-17
相关资源
最近更新 更多