[英]Two Variable side by side bar plot ggplot
嘗試繪制並排的條形圖,但條形圖似乎相互靠攏,但無法使其並排: 參見圖像
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")
為了被視為分類變量,您的Year
列需要轉換為type 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.