使用R中的barplot函数绘制区间图

3
我正在使用这个问题中的解决方案来尝试绘制具有指定间隔的条形图: 基于范围在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

我不知道如何修复这个错误。是否有更简单的方法来创建像这样的条形图中的分组区间,或者是否有人对如何使区间与条形图配合有任何建议?
谢谢!

3
在这种情况下,你可能应该使用“cut”,而不是“shingle”。 - bouncyball
1个回答

5
我以前没有使用过“shingle”函数,但它似乎是用于创建石板图而不是条形图的,尽管可能有一种我不知道的方法可以使用“shingle”对象创建条形图。无论如何,下面的代码显示了如何使用基本图形,“lattice”或“ggplot2”来创建条形图,但使用“cut”函数创建条目。
关于您收到的错误需要注意的问题:“barplot”是一个基本图形函数。它期望将数字向量作为其第一个参数作为条形高度值。但是,“shx”是一个“shingle”对象,而不是高度向量,因此会出现错误。原则上,有人可以为“barplot”编写一个“shingle方法”,使“barplot”从“shingle”对象返回条形图,但是当前不存在这样的方法,并且不必要,因为有其他“标准”方法来创建条形图。
如下所示,绘制一个“shingle”对象的方法是只需调用通用的“plot”函数,因为“plot”“知道”当它接收到一个“shingle”对象时,应该返回一个“lattice” shingle图。如果您运行“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)

格子状木瓦图
plot(shx)

enter image description here

现在让我们设置创建条形图的数据。我们将使用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)

基础图形条形图

barplot(table(data5$breaks), horiz=TRUE, las=1)

enter image description here

lattice 条形图

barchart(data5$breaks)

enter image description here

ggplot2 条形图

library(ggplot2)

ggplot(data5, aes(breaks)) +
  geom_bar() + 
  coord_flip() +
  theme_bw()

enter image description here


哇,太棒了。我从没想到它会这么简单。非常感谢你详细的解释和图形。 - nchimato

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接