E.A.
E.A.

Reputation: 21

r ggplot geom_bar grouped position

I want a barplot showing prevalence~delta, grouped on the x axis by omega. Delta has 8 levels and omega has 5.

I would like my plot to look like this example: example ggplot

the code for this plot is:

ggplot(data=dat1, aes(x=time, y=total_bill, fill=sex)) +
    geom_bar(stat="identity", position=position_dodge(), colour="black")

My code produces a plot where levels of delta are stacked vertically, even though I used the position= position_dodge() argument.

ggplot(mydata, aes(x=omega, y=Prevalence, fill=delta)) + 
  geom_bar( stat = "identity", position = position_dodge())

my ggplot

my data:

   delta omega Prevalence
1    0.0   0.0      0.040
2    0.1   0.0      0.065
3    0.2   0.0      0.082
4    0.3   0.0      0.096
5    0.5   0.0      0.118
6    1.0   0.0      0.147
7    2.0   0.0      0.162
8    4.0   0.0      0.149
9    0.0   0.3      0.072
10   0.1   0.3      0.097
11   0.2   0.3      0.114
12   0.3   0.3      0.125
13   0.5   0.3      0.140
14   1.0   0.3      0.155
15   2.0   0.3      0.155
16   4.0   0.3      0.128
17   0.0   0.5      0.083
18   0.1   0.5      0.108
19   0.2   0.5      0.123
20   0.3   0.5      0.133
21   0.5   0.5      0.145
22   1.0   0.5      0.154
23   2.0   0.5      0.146
24   4.0   0.5      0.113
25   0.0   0.7      0.090
26   0.1   0.7      0.114
27   0.2   0.7      0.128
28   0.3   0.7      0.137
29   0.5   0.7      0.146
30   1.0   0.7      0.150
31   2.0   0.7      0.135
32   4.0   0.7      0.098
33   0.0   1.0      0.095
34   0.1   1.0      0.118
35   0.2   1.0      0.130
36   0.3   1.0      0.137
37   0.5   1.0      0.142
38   1.0   1.0      0.139
39   2.0   1.0      0.118
40   4.0   1.0      0.077

Upvotes: 2

Views: 2951

Answers (1)

JereB
JereB

Reputation: 137

The problem here is that delta is coded as numeric. Simply change it to a factor and then it works.

ggplot(mydata, aes(x=omega, y=Prevalence, fill=as.factor(delta))) + 
  geom_bar( stat = "identity", position = position_dodge())

enter image description here

Upvotes: 2

Related Questions