Ibrahim EL-Sanosi
Ibrahim EL-Sanosi

Reputation: 71

ggplot Error bars does not fit on its bars

I would like to have bar chart with its error bars.

I have data as following:

data <- read.table(text = "Write.Ratio Latency  Systems ErrorBar

25  33.68947433 ZAc 0.584923265

50  35.95189364 ZAc 0.533620214

75  37.61611343 ZAc 0.478412112

100 38.94321815 ZAc 0.613659804

25  34.88948194 ZAa 0.668849228

50  37.50136427 ZAa 0.810768079

75  38.32180932 ZAa 0.855439587

100 40.11655606 ZAa 1.016661533

25  44.54909217 Z   2.743318523

50  45.11834046 Z   2.694675714

75  47.58457625 Z   3.848277026

100 51.54500237 Z   3.11271401

100 39.93495434 ZCt 1.042499708", header = TRUE)

The script to draw the bars and its error bars as follows:

data <- transform(data,Systems=reorder(Systems,order(Latency, decreasing=F)))
plot1 <- ggplot(data, aes(Write.Ratio, Latency, fill=Systems))

plot1 <- plot1 +geom_bar(stat = "identity",position="dodge")+
  geom_errorbar(aes(ymin=Latency-ErrorBar, ymax=Latency+ErrorBar))

plot1 <- plot1+scale_y_continuous(breaks= seq(0,60,10))+labs(x = "Write Ratio")+
  scale_x_continuous(breaks= seq(0,100,25))+labs(y="Latency (ms)")

plot1 <- plot1+scale_fill_manual(values=c("#2980b9", "#F5BF00", "#66CC99", "#6c3483"))

plot1 <- plot1+theme(panel.grid.major = element_blank())

plot1 <- plot1+theme_bw()+theme(legend.position="bottom")+labs(fill="")+
  theme(text = element_text(size=18))

plot1

enter image description here

When I run the script, I have two problems: (1) the error bars are over their bars (they does not place exactly on its bars) and (2) the error bars looks very large.

Any help to fix these issues?

Upvotes: 0

Views: 873

Answers (1)

Jake
Jake

Reputation: 520

I think everything they told you in the comments above does work. See below.

#Turn Write.Ratio into a factor
data$Write.Ratio <- as.factor(data$Write.Ratio)

data <- transform(data,Systems = reorder(Systems, order(Latency, decreasing = F)))
plot1 <- ggplot(data, aes(Write.Ratio, Latency, fill = Systems))

#Add position=position_dodge(.9) to geom_errorbar
plot1 <- plot1 + geom_bar(stat = "identity", position="dodge") +
  geom_errorbar(aes(ymin=Latency-ErrorBar, ymax=Latency+ErrorBar), width = .2, position=position_dodge(.9))

plot1 <- plot1+scale_y_continuous(breaks= seq(0,60,10))+labs(x = "Write Ratio")+
  scale_x_discrete(labels = seq(25,100,25))+ labs(y="Latency (ms)")

plot1 <- plot1+scale_fill_manual(values=c("#2980b9", "#F5BF00", "#66CC99", "#6c3483"))

plot1 <- plot1+theme(panel.grid.major = element_blank())

plot1 <- plot1+theme_bw()+theme(legend.position="bottom")+labs(fill="")+
  theme(text = element_text(size=18))

plot1

enter image description here

Upvotes: 3

Related Questions