2017-02-22 133 views
1

Image of sample data两种可变并排条形图ggplot

试图让并排条形图侧,但酒吧似乎是在彼此的后面,但不能让他们并排:看到图像

enter image description here

afg <- read.table(header=TRUE, 
text="FG biomass stdev Year 
1 287.6 237.5 2015 
1 254.2 220.6 2016 
2 309.9 126.3 2015 
2 307.6 139.5 2016 
3 339.6 175.5 2015 
3 349.3 160.6 2016") 

library(ggplot2) 
ggplot(afg,aes(afg$FG,afg$biomass,fill=afg$Year)) + 
geom_bar(stat="identity",position=position_dodge(0.9),color="black") 

library(reshape2) 
afg.long <- melt(afg$Year,id="year") 
ggplot(afg.long,aes(afg$FG,afg$biomass,fill=afg$Year)) + 
geom_bar(stat="identity",position = "dodge") 
+0

我已经添加了我的数据是如何设置 –

+0

如果你点击这个数字我想它会弹出一个图片,对不起,如果我没有做这个正确的,这是我第一次 –

回答

2

为了被视为分类变量,要转换色谱柱Year需要键入factor。另请注意,在aes()函数内不应使用$的变量选择。

library(ggplot2) 

p <- ggplot(afg, aes(x=FG, y=biomass, fill=factor(Year))) + 
    geom_bar(stat="identity", position="dodge") 

ggsave("dodged_barplot.png", plot=p, height=4, width=6, dpi=150) 


# Note that 'Year' is type integer. 

str(afg) 
# 'data.frame': 6 obs. of 4 variables: 
# $ FG  : int 1 1 2 2 3 3 
# $ biomass: num 288 254 310 308 340 ... 
# $ stdev : num 238 221 126 140 176 ... 
# $ Year : int 2015 2016 2015 2016 2015 2016 

enter image description here

+0

谢谢,明白了! –