试图制作一个并排的条形图,但条形图似乎在彼此之后,但不能让它们并排:看图像
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 :(得分: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