如何在ggplot2 r

时间:2015-07-15 18:42:59

标签: r ggplot2

我是r的新手并尝试使用ggplot2制作分组的条形图。我已经完成了绘图,但是我在重新排序数据时遇到了问题,并且格式化了美学图。

我使用的代码是:

# ggplot2 for bar graphs by time and treatment 

df<-read.csv(file.choose(), header = TRUE)
attach(df)
install.packages("ggplot2") # install ggplot2 package
require(ggplot2) # load package 
Treatment<-c(TreatID)
Treatment<-as.factor(Treatment)
Year<- as.factor(Year)

# year and treatment 
x<-sd(PF) # 12.98009
x<- PF
std <- function(x) sd(x)/sqrt(length(x)) #calculation of standard error
se<- std(x) # .2420988
se<-(0.2420988)


p<-ggplot(df, aes(x= Year, y= PF, fill= TreatID), scale_colour_grey) + geom_bar(position=position_dodge(), stat= "identity") + ggtitle("Percent Cover Perennial Forbs by Treatment")  + scale_x_continuous(breaks= c(2009, 2010, 2011, 2015), labels=c("SMCU", "SMCS", "SMBU", "SMBS", "SMPS", "SMLS")) + ylab("% Cover Perennial Forbs") + geom_errorbar(aes(ymin= PF - se, ymax = PF + se), width= .2, position = position_dodge(.9)) # add error bars 
p + ylab("% Cover Perennial Forbs")
(p = p + scale_fill_grey(start = 0, end = .9)) #makes bars grey
(p = p + theme_bw()) #changes chart background to white

2011年和2015年之间存在很大的差距我想要删除,需要重新安排TreatID,以便首先使用“SMCU”,然后是“SMCS”,“SMBU”,“SMBS”,“SMLS”和然后“SMPS”。

任何建议都将不胜感激!

1 个答案:

答案 0 :(得分:0)

要消除差距,请确保将年份视为一个因素。并且,为了改变治疗的顺序,重新排序因子。

## Some sample data
dat <- data.frame(Year=factor(rep(c(2009:2011, 2015), each=6)),
                  TreatID=factor(rep(c("SMCU", "SMCS", "SMBU", "SMBS", "SMPS", "SMLS"), 4)),
                  PF=runif(4*6))


## Reorder your TreatID levels
dat$TreatID <- factor(dat$TreatID, levels=c("SMCU", "SMCS", "SMBU", "SMBS", "SMLS", "SMPS"))
se <- 0.242

## Make sure Year is a factor so there is no gap
p <- ggplot(dat, aes(x=as.factor(Year), y= PF, fill= TreatID), scale_colour_grey) +
  geom_bar(position=position_dodge(), stat= "identity") +
  ggtitle("Percent Cover Perennial Forbs by Treatment")  +
  ylab("% Cover Perennial Forbs") +
  geom_errorbar(aes(ymin= PF - se, ymax = PF + se), width= .2, position = position_dodge(.9)) +
  scale_fill_grey(start = 0, end = .9) +
  theme_bw()
p

enter image description here