ggplot条形图额外的空间
我试图绘制R.使用ggplot图这里是我的代码:ggplot条形图额外的空间
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))
我的问题是,无论我怎么努力,我无法摆脱绘图区域的额外空间。任何建议将不胜感激。
在你的代码的主要问题是,有在水平的顺序错误变量Length
。 您可以使用函数factor()
和参数levels=dfw$Length
修复它(因为您的原始数据帧的顺序是正确的)。
data.long$Length<-factor(data.long$Length,levels=dfw$Length)
现在您不需要使用scale_x_discrete()
来设置限制。
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))
太棒了,它像一个魅力。非常感谢。 – user690462 2013-03-09 19:47:06
删除此scale_x_discrete(limits = data.long$Length)
,然后再试一次希望这有助于
编辑:通过删除该删除在Y,如果你有它scale_y_discrete(limits = data.long$Length)
我试过了,但它重新排列了x轴。 – user690462 2013-03-09 19:36:31
你在这里设置了限制:'scale_x_discrete(limits = data.long $ Length)'。你尝试删除它吗? – Arun 2013-03-09 19:32:15
是的,然后重新排列x轴。 – user690462 2013-03-09 19:36:57