使用 barplot 函数 R 绘制区间

nch*_*ato 3 r intervals bins bar-chart lattice

我正在使用这个问题中的解决方案来尝试绘制具有指定间隔的条形图:

根据范围在 R 中创建分类变量

我创建了间隔并尝试在函数中使用它们barplot,但我显然在某个地方缺少一个步骤,并且我不确定如何让它工作。这是我的代码和我收到的错误:

> library(lattice)

> a = c(0,10)
> b = c(11,20)
> c = c(21,30)
> d = c(31,40)
> e = c(41,50)
> f = c(51,60)
> g = c(61,70)
> h = c(71,80)
> i = c(81,90)
> j = c(91,100)
> k = c(101,120)
> l = c(121,150)
> m = c(151,200)
> n = c(201,500)
> o = c(501,3600)

> mybins = matrix(rbind(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o), ncol=2)
> shx <- shingle(data5$q3totalScleralLensesFit, intervals=mybins)
> shx
  Intervals:
  min  max count
  1    0   10   140
  2   11   20   117
  3   21   30    78
  4   31   40    31
  5   41   50    72
  6   51   60     5
  7   61   70     6
  8   71   80    28
  9   81   90     3
  10  91  100    49
  11 101  120     7
  12 121  150    28
  13 151  200    25
  14 201  500    61
  15 501 3600    28

> bp <- barplot(shx, main="", xlab="", ylim=c(0,160), ylab="", las=2, cex.names=0.75)

Error in barplot.default(shx, main = "", xlab = "", ylim = c(0, 160),  : 
'height' must be a vector or a matrix
Run Code Online (Sandbox Code Playgroud)

我不知道如何修复该错误。有没有更简单的方法来为条形图制作这样的垃圾箱,或者有人对如何使间隔与条形图一起工作有任何建议吗?

谢谢你!

eip*_*i10 5

我以前没有使用过该shingle函数,但它似乎是为了创建木瓦图而不是条形图而设置的,尽管可能有一种我不知道的方法可以使用木瓦对象创建条形图。无论如何,下面的代码显示了如何使用基本图形 、lattice或 来创建条形图ggplot2,但使用该cut函数来创建条形图。

关于您收到的错误,需要注意的一个问题barplot是:基本图形函数。它期望将条形高度值的数字向量作为其第一个参数。但shx它是一个木瓦对象,而不是高度向量,因此会出现错误。原则上,有人可以编写一个“shingle 方法”,它barplot可以barplot从对象返回条形图shingle,但这样的方法目前不存在,也没有必要,因为还有其他“标准”方法来创建条形图阴谋。

如下所示,绘制shingle对象的方法只需调用通用plot函数,因为plot“知道”当它接收到shingle对象时,它应该返回一个lattice木瓦图。如果您运行,methods(plot)您将看到plot有数十种“方法”(包括plot.shingle)来确定做什么plot,具体取决于提供给plot函数的对象类型。

## Fake data
set.seed(5)
data5 = data.frame(q3totalScleralLensesFit = runif(1000,0,3600))

## Create shingle object

# Easier way to create bins
bins = c(0, seq(11,101,10),121,151,201,501,3601)
mybins = cbind(bins, lead(bins) - 1)[-length(bins),]

shx <- shingle(data5$q3totalScleralLensesFit, intervals=mybins)
Run Code Online (Sandbox Code Playgroud)

格子木瓦图

plot(shx)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

现在让我们设置用于创建条形图的数据。我们将使用该cut函数:

# Create bins using cut function
data5$breaks = cut(data5$q3totalScleralLensesFit, 
                   breaks=c(seq(0,100,10),120,150,200,500,3600),
                   include.lowest=TRUE)
Run Code Online (Sandbox Code Playgroud)

基础图形条形图

barplot(table(data5$breaks), horiz=TRUE, las=1)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

lattice条形图

barchart(data5$breaks)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

ggplot2条形图

library(ggplot2)

ggplot(data5, aes(breaks)) +
  geom_bar() + 
  coord_flip() +
  theme_bw()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述