9

我正在尝试在 R 中绘制这些数据-

column1  column2  column3
1-2       abc       10
1-2       def       15
1-2       ghi       20
2-3       abc       80
2-3       def       95
2-3       ghi       10
3-4       abc       30
3-4       def       55
3-4       ghi       80

x 轴将是 column1(因此 1-2、2-3 和 3-4 将作为 x 轴出现),并且在 y 轴上,应为每个 column2 元素绘制 column3 中的值。所以这本质上是一个“分组”的条形图。

我无法使用 R 绘制此分组条形图。我使用的代码片段如下:

dataset <- fetch(rs,n=-1)
plot_var <- table(dataset$percentage, dataset$age)
barplot(plot_var, names.arg,
        main="Title of Graph",
        xlab="Column1", col=c("darkblue","red"),
        legend = rownames(plot_var), beside=TRUE)

如何让这个分组条形图显示?谢谢!

4

3 回答 3

15

Your problem seem to come down to wrong data formatting. You need to make a matrix with the right row names structure to create plot that you want with base graphics. Here is your solution:

#your data...
d <- data.frame(row.names=c("1-2","2-3","3-4"), abc = c(10,80, 30), 
                def = c(15, 95, 55), ghi = c(20, 10, 80))
#but you make a matrix out of it to create bar chart
d <- do.call(rbind, d)
#...and you are sorted
barplot(d, beside = TRUE, ylim=c(0,100), legend.text = rownames(d), 
        args.legend = list(x = "topleft", bty="n"))

enter image description here

However, I sometimes like to use lattice for this kind of task. This time you don't even have to make matrix, you just keep your data.frame in original format:

d <- data.frame(column1=rep(c("1-2","2-3","3-4"), each=3), 
                column2=rep(c("abc", "def", "ghi"), 3), 
                column3=c(10, 15, 20, 80, 95, 10, 30, 55, 80))
require(lattice)
barchart(column3 ~ column1, groups=column2, d, auto.key = list(columns = 3))

enter image description here

于 2012-11-03T22:37:46.483 回答
10

I like to use ggplot2 for this kind of task.

#Make the data reproducible:
column1 <- c(rep("1-2", 3), rep("2-3", 3), rep("3-4", 3))
column2 <- gl(3, 1, 9, labels=c("abc", "def", "ghi"))
column3 <- c(10, 15, 20, 80, 95, 10, 30, 55, 80)

d <- data.frame(column1=column1, column2=column2, column3=column3)

require(ggplot2)
ggplot(d, aes(x=column1, y=column3, fill=column2)) + geom_bar(position=position_dodge())

The reason I find this intuitive (after a bit of a learning period) is that you clearly stated what you want on the x and y axes, and we simply tell ggplot that (as well as which variable defines the 'fill' color, and which kind of plot - here, geom_bar - to use.

enter image description here

于 2012-11-03T20:12:35.560 回答
1

我从 Drew Steen 的回答中找到了帮助,但上面的代码对我不起作用,如上所示。我添加了 stat="identity" 并且它有效。

require(ggplot2)
ggplot(d, aes(x=column1, y=column3, fill=column2)) + geom_bar(stat="identity", position=position_dodge())

谢谢德鲁的回答。

于 2017-01-19T11:46:55.477 回答