Reputation: 1249
I have the dataframe p3 below:
test result
1 1 26.87778
2 1 24.52598
3 1 24.02202
4 1 20.32632
5 1 22.00618
6 2 19.84013
7 2 19.68983
8 2 19.84013
9 2 19.23892
10 2 19.23892
11 3 34.36430
12 3 33.28196
13 3 33.82313
14 3 33.82313
15 3 32.47020
16 4 25.55169
17 4 26.90442
18 4 25.40138
19 4 24.19895
20 4 25.85230
21 4 25.70199
22 4 24.95047
23 5 18.64646
24 5 18.64646
25 5 17.80653
26 5 18.64646
27 5 18.31049
I am trying to make a barchart with dodged results using the code:
ggplot(p3, aes(x = test, y = result))+ geom_bar(position="dodge", stat="identity")
but it doesn't work at all. I don't understand why it is not working since I used the same code before and it worked.
Upvotes: 10
Views: 21552
Reputation: 1249
This was answered by Dennis Murphy:
p3$test <- factor(p3$test)
p3$fac <- factor(unlist(sapply(as.vector(table(p3$test)), seq_len)))
ggplot(p3, aes(x = test, y = result, fill = fac)) +
geom_bar(position = 'dodge', stat = 'identity')
Adjusting the variables:
ggplot(p3, aes(x = test, y = result, color = fac, fill = test)) +
geom_bar(position = 'dodge', stat = 'identity', linetype = 0)
I almost got what I wanted, except that the color (outline) should be the same. but it was close enough.
Upvotes: 1
Reputation: 43265
ggplot(p3, aes(x = test, y = result, group = result)) +
geom_bar(position="dodge", stat="identity")
you can see what is happening if you change the group
argument to color
.
ggplot(p3, aes(x = test, y = result, color = result)) +
geom_bar(position="dodge", stat="identity")
Edited for comments:
It looks like there are odd numbers of groups because there are. Group 4 has 7 elements in it in the data you supplied. group 3 has 5 but 2 of them are identical. The plot shows the height correctly and is grouping like elements together. its like you called unique
on each group.
I think plotting:
ggplot(p3, aes(x=test, y=result, group=result, color=result)) +
geom_bar(position='dodge', stat='identity')
displays this quite well. As far as each group having 5 elements, that isn't the case. Group 4 has 7. To see what you're describing you could do something like:
ggplot(p3, aes(x=as.integer(row.names(p3)), y=result, fill=factor(test))) +
geom_bar(position='dodge', stat='identity')
Upvotes: 12