需要使用R为大数据绘制条形图

时间:2013-07-09 03:44:09

标签: r

我在.csv文件中有以下数据:

Name  marks1 marks2    
xy      10    30
yz      20    40
zx      30    40
vx      20    20
vt      10    20

如何在y轴上绘制marks1marks2的图形,在x轴上绘制名称?

y <- cbind(data$marks1,data$marks2)
x <- cbind(data$Name)
matplot(x,y,type="p")

我需要一个条形图,由于x轴数据量很大,我需要正确地对齐它们并放置数字

例如图表应该像

在同一条中用两种不同颜色标记1标记2并在其上写上标记

#read csv file
 aau <- read.csv("",head=TRUE,sep=",")

#convert into matrix format
 aaumatrix <- as.matrix(aau)

#create barplot
 barplot(aaumatrix)


#check for more attributes of barplot
 ?barplot

1 个答案:

答案 0 :(得分:1)

你想要的描述有点令人困惑,但这是我最好的解释。

dat <- read.table(textConnection("Name  marks1 marks2                                                                                  
xy      10    30                                                                                                                       
yz      20    40                                                                                                                       
zx      30    40                                                                                                                       
vx      20    20                                                                                                                       
vt      10    20"), header = TRUE)

library(ggplot2)
library(reshape)

datm <- melt(dat, id.vars = "Name")

datlab <- dat
datlab$y <- datlab$marks1
datlab <- melt(datlab, id.vars = c("Name", "y"))

## set y value to be in the center of the respective bar 
datlab$y <- ifelse(datlab$variable == "marks1", datlab$y / 2, datlab$y + datlab$value / 2)

p <- ggplot() + geom_bar(data = datm, aes(value, x = Name, fill = variable))
p + geom_text(data = datlab, aes(x = Name, y = y, label = value))

修改:另一个选项

datlab <- dat
datlab$y <- rowSums(datlab[c("marks1", "marks2")])
datlab <- melt(datlab, id.vars = c("Name", "y"))
## set y value to be in the center of the respective bar                                                                               
datlab$y <- ifelse(datlab$variable == "marks1", datlab$value / datlab$y / 2, 1 - datlab$value / datlab$y / 2)

p <- ggplot() + geom_bar(data = datm, aes(x = Name, fill = variable, y = value), position = "fill")
p + geom_text(data = datlab, aes(x = Name, y = y, label = value))

选项1:

enter image description here 选项2:

enter image description here