创建条形图R以进行覆盖

时间:2012-03-27 15:45:25

标签: r ggplot2

我想创建一个条形图,我的数据采用以下格式的csv文件

0,22
40,50
80,62
120,70
160,62
200,49
240,52
280,64
320,57
360,50
400,47
440,52
480,73
520,70
560,68
600,71
640,69
680,61
720,59
760,59
800,62
840,62
880,62
920,72
960,81
1000,89
1040,86
1080,76
1120,80
1160,95

逗号前面的元素应该是x轴中的位置,逗号后面的元素应该是该位置上条形的高度=。我可以在Excel中执行此操作,但数据很大。 我想要的图表看起来像这样。

enter image description here

我尝试了以下内容,但我认为它总结了每一行中的数据。

data <- as.matrix(read.csv(file="data.csv",sep=",",header=FALSE))
barplot(data)

3 个答案:

答案 0 :(得分:4)

barplot(x$V2, names.arg = seq_len(nrow(x)), cex.names = .6)

enter image description here

答案 1 :(得分:2)

两件事:首先,如果你将整个矩阵提供给barplot的height参数,它会将它们相加。相反,只给它你的数据。

dput(dat)
structure(c(0L, 40L, 80L, 120L, 160L, 200L, 240L, 280L, 320L, 
360L, 400L, 440L, 480L, 520L, 560L, 600L, 640L, 680L, 720L, 760L, 
800L, 840L, 880L, 920L, 960L, 1000L, 1040L, 1080L, 1120L, 1160L, 
22L, 50L, 62L, 70L, 62L, 49L, 52L, 64L, 57L, 50L, 47L, 52L, 73L, 
70L, 68L, 71L, 69L, 61L, 59L, 59L, 62L, 62L, 62L, 72L, 81L, 89L, 
86L, 76L, 80L, 95L), .Dim = c(30L, 2L), .Dimnames = list(NULL, 
    c("V1", "V2")))

barplot(height=dat[,2])

第二,您需要向条形图提供names.arg以获得标签:

barplot(height=dat[,2], names.arg=dat[,1])

附注:最好避免使用内置R函数命名变量。 ?data可能是最常被覆盖的!我经常使用dat

答案 2 :(得分:1)

使用您将数据输入R:

的方法
myData <- read.csv(file = "data.csv", sep = ",", header = FALSE)

确保条形的顺序遵循第一列中值的顺序(尽管这不是您在问题中要求的严格要求)

myData2 <- myData[order(myData[, 1]), ]

barplot(myData2[, 2], names.arg = myData2[, 1])

A barplot

为了调整图表,我建议您花点时间阅读?barplot?par