Reputation: 129
I am trying to draw a graph using ggplot in R. Here are my codes:
library(reshape2)
library(ggplot2)
dfw <- read.table(header=T, text='
Length L1 L2
200:399 27665 28483
400:599 9232 11856
600:799 3347 4072
800:999 1923 2112
1000:1199 1322 1511
1200:1399 955 1118
1400:1599 693 850
1600:1799 496 640
1800:1999 332 463
2000:2199 219 306
2200:2399 142 212
2400:2599 73 134
2600:2799 65 121
2800:2999 39 87
3000:3199 19 57
3200:3399 20 31
3400:3599 14 37
3600:3799 4 22
3800:3999 2 17
4000:9599 8 53
')
data.long <- melt(data = dfw, id.var = "Length",
measure.vars = c("L1", "L2"), variable.name = "Condition")
ggplot(data=data.long, aes(x=Length, y=value, fill=Condition)) +
geom_bar(stat="identity", position=position_dodge(width = 1),
colour="black", na.rm = TRUE, width = 0.5) +
scale_x_discrete(limits = data.long$Length) +
theme(axis.title.x = element_text(face="bold", colour="#990000", size=20),
axis.text.x = element_text(angle=90, vjust=2, size=16))
My problem is no matter what I try, I cannot get rid of the extra space in the plotting area. Any advise would be appreciated.
Upvotes: 1
Views: 1258
Reputation: 1605
Remove this scale_x_discrete(limits = data.long$Length)
and try again hope this helps
EDIT : Remove the Y to by removing this if you have it scale_y_discrete(limits = data.long$Length)
Upvotes: 1
Reputation: 98439
The main problem in your code is that there are wrong order of levels in variable Length
.
You can fix it with function factor()
and argument levels=dfw$Length
(as your original data frame has correct order).
data.long$Length<-factor(data.long$Length,levels=dfw$Length)
Now you don't need to use scale_x_discrete()
to set limits.
ggplot(data=data.long, aes(x=Length, y=value, fill=Condition)) +
geom_bar(stat="identity", position=position_dodge(width = 1), colour="black", na.rm = TRUE, width = 0.5) +
theme(axis.title.x = element_text(face="bold", colour="#990000", size=20),
axis.text.x = element_text(angle=90, vjust=2, size=16))
Upvotes: 2