在R中用直方图格式化x轴

时间:2014-03-12 07:41:15

标签: r plot drawing histogram

我希望x轴从1到20,y轴从1到6。 我的数据:

structure(list(HEI.ID = structure(c(12L, 9L, 14L, 19L, 20L, 1L, 
7L, 5L, 11L, 3L, 10L, 18L, 2L, 8L, 6L, 15L, 13L, 17L, 4L, 16L
), .Label = c("BF", "CC", "DC", "ER", "IM", "MC", "ME      ", 
"MM", "MO", "OC", "OM", "OP", "SB", "SD", "SH", "SL", "SN", "TH", 
"UN", "WS"), class = "factor"), X2007 = c(18L, 14L, 15L, 20L, 
12L, 6L, 17L, 2L, 4L, 11L, 16L, 1L, 9L, 8L, 13L, 4L, 10L, 6L, 
3L, 19L), X2008 = c(20L, 9L, 16L, 18L, 8L, 17L, 15L, 6L, 3L, 
14L, 19L, 1L, 2L, 12L, 5L, 13L, 11L, 7L, 4L, 10L), X2009 = c(20L, 
13L, 17L, 8L, 4L, 9L, 19L, 12L, 2L, 11L, 16L, 1L, 2L, 7L, 6L, 
18L, 5L, 15L, 9L, 14L), X2010 = c(20L, 13L, 16L, 13L, 7L, 15L, 
19L, 8L, 3L, 9L, 18L, 1L, 5L, 11L, 12L, 6L, 10L, 4L, 2L, 17L), 
    X2011 = c(20L, 2L, 16L, 14L, 6L, 10L, 17L, 8L, 3L, 15L, 19L, 
    1L, 4L, 18L, 13L, 11L, 8L, 12L, 4L, 7L), X2012 = c(20L, 12L, 
    19L, 13L, 8L, 14L, 15L, 10L, 11L, 9L, 17L, 2L, 7L, 18L, 5L, 
    16L, 3L, 4L, 6L, 1L)), .Names = c("HEI.ID", "X2007", "X2008", 
"X2009", "X2010", "X2011", "X2012"), row.names = c(NA, -20L), class = "data.frame")

我使用以下命令绘制直方图:

par(mfrow = c(3,4))
for(i in  1:20){
  print(i)
  hist(as.numeric(HEIrank11[i,-1]),nclass=12,,main='students/faculty',
       xlab = STOF[i,1],cex.lab=1, cex.axis=1, cex.main=1, cex.sub=1)
 }

但是在使用上述命令后,我在x轴和y轴上得到不同的数字。

2 个答案:

答案 0 :(得分:1)

我不明白你的情节会是什么样子。从您提供的问题和数据中不清楚。

我试图策划它。如果您认为这是最佳选择,请发表评论。

考虑dt是您的data.frame

library(reshape)
dt <- melt(dt)
library(ggplot2)
ggplot(aes(x=HEI.ID, y = value, fill = variable), data = dt) +
  geom_bar(stat = 'identity')

histogram

ggplot(aes(x=HEI.ID, y = value, fill = variable), data = dt1) +
  geom_bar(stat = 'identity') +
  facet_grid(variable ~.)

enter image description here

答案 1 :(得分:0)

您可以在xlim函数中使用ylimhist参数并使用控制轴 axis

par(mfrow = c(3,4))
for(i in  1:12){
  print(i)  
  hist(as.numeric(HEIrank11[i,-1]),nclass=12,,main='students/faculty',
       xlim=c(0, 21), ylim=c(0,6), xaxt='n', yaxt='n')
  axis(1, at=c(0, 10, 20))
  axis(2, at=0:6)  
}

你真的希望你的y轴从1到6吗?这将切断部分条形。 此外,您将迭代所有20行以获得具有12个图的网格。上面的代码给出了以下图:

enter image description here