使用条形图函数R

时间:2016-06-20 15:59:51

标签: r bar-chart intervals lattice bins

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

Create categorical variable in R based on range

我创建了我的间隔,并尝试在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

我不知道如何修复错误。是否有更容易的方法为条形图制作这样的垃圾箱,或者是否有人对如何使间隔与条形图一起使用有任何建议?

谢谢!

1 个答案:

答案 0 :(得分:4)

之前我没有使用过shingle函数,但它似乎是为了创建一个木瓦图而不是条形图而设置的,尽管可能有一种方法我不知道使用木瓦对象创建条形图。在任何情况下,下面的代码都显示了如何使用基本图形latticeggplot2创建条形图,但使用cut函数创建条形图。

根据您收到的错误需要注意的问题:barplot是基本图形功能。它期望条形高度值的数字向量作为其第一个参数。但是shx是一个瓦片对象,而不是高度的向量,因此是错误。原则上,有人可以为barplot编写一个“shingle方法”,使barplotshingle对象返回一个条形图,但这种方法目前还不存在因为有其他“标准”方法来创建条形图,所以这是必要的。

如下所示,绘制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)

Lattice shingle plot

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

相关问题