分组条形图 [英] Grouping bar plots
问题描述
我正在尝试对两个条形图进行分组,但是到目前为止,我还没有成功...我遵循了这个找到几个不错的 ggplot
示例.
library(reshape2)库(ggplot2)df<-熔体(计数)ggplot(数据= df,aes(x = as.factor(Var1),y =值,fill = Var2))+geom_bar(stat ="identity",position ="dodge")
I'm trying to group two barcharts, but I haven't been successful so far... I followed this example, but the output is not as desired. The bars are one behind the other instead of next to each other.
Here's the line of code I use:
barplot(as.matrix(counts),xaxt='n', col=c("white","blue"), ylim=c(0.1,1300), axes=FALSE, beside=T, space = 1.4, mar=c(5,5,5,5))
When I try this...
> barplot(as.matrix(counts), beside = TRUE)
> barplot(as.matrix(counts), beside = TRUE, space = c(0, 1.4))
... I get this plot:
And this is my data frame, in case that causes the problem:
> counts
V1 V2
1 26 50
2 50 86
3 86 50
4 50 50
5 50 50
6 50 100
7 100 150
8 150 350
9 350 50
10 50 28
11 28 300
12 300 250
13 250 300
14 300 250
15 250 300
16 300 500
17 500 400
18 400 0
19 600 0
20 500 0
21 1250 0
> dput(counts)
structure(list(V1 = c(26, 50, 86, 50, 50, 50, 100, 150, 350,
50, 28, 300, 250, 300, 250, 300, 500, 400, 600, 500, 1250), V2 = c(50,
86, 50, 50, 50, 100, 150, 350, 50, 28, 300, 250, 300, 250, 300,
500, 400, 0, 0, 0, 0)), .Names = c("V1", "V2"), row.names = c(NA,
-21L), class = "data.frame")
Any ideas?
I think the problem is that you only provide one space
value. From ?barplot
: " If height is a matrix and beside is TRUE, space may be specified by two numbers, where the first is the space between bars in the same group, and the second the space between the groups. If not given explicitly, it defaults to c(0,1) if height is a matrix and beside is TRUE".
Try this:
barplot(as.matrix(counts), beside = TRUE)
barplot(as.matrix(counts), beside = TRUE, space = c(0, 1.4))
Update following comments
Given that you seem to want bars grouped by row, rather than column (referring to the original data), you need to transpose your matrix to a 'wide' format. In barplot
each column of the input matrix corresponds to a group of bars, and each row to different bars within groups. As your original data was organized, the two columns V1 and V2 represented the groups. Thus the plot resulting from my script above have two groups with 21 bars each. After transposing, you will get a plot with 21 groups with two bars each.
barplot(t(as.matrix(counts)), beside = TRUE)
I add a ggplot
example for comparison. In ggplot
the data should be a data frame in a long format. Thus, first we need to 'melt' the data. Here I use the melt
function from package reshape2
. You find several nice ggplot
examples here.
library(reshape2)
library(ggplot2)
df <- melt(counts)
ggplot(data = df, aes(x = as.factor(Var1), y = value, fill = Var2)) +
geom_bar(stat = "identity", position = "dodge")
这篇关于分组条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!