How to plot the same bar twice (or multiple times) in R

I try to plot the same bar multiple times in the same graph using ggplot.

My code (I want to plot Empetrum_ three times in the graph):

temp10A <- ggplot(data, aes(x=Combination, y=Max.Max.Temp, fill=Combination)) 
+ geom_bar(position=position_dodge(), stat="identity") 
+ geom_errorbar(aes(ymin=Max.Max.Temp-se, ymax=Max.Max.Temp+se), width=.2,  position=position_dodge(.9)) 
+ scale_x_discrete(limits=c(**"Empetrum_"**, "Calluna_", "Empetrum_Calluna" , "Pleurozium_", "Hypnum_", "Pleurozium_Hypnum", "Pleurozium_", "Calluna_","Pleurozium_Calluna", "Hypnum_", "Empetrum_"**,"Hypnum_Empetrum", "Hypnum_", "Calluna_","Hypnum_Calluna" , "Pleurozium_", **"Empetrum_"**, "Pleurozium_Empetrum")) 
+ theme(axis.text.x = element_text(angle = 45, hjust = 1))

As you can see it leaves out the second and third time I would like to plot Empetrum_. The same thing holds for the Hypnum_, Pleurozium_ and Calluna_ when I want to plot them multiple times.

Does anyone know how to avoid this automated leaving out of replicates or have another sollution?

Thank you in advance.


I don't believe this is actually possible within ggplot . But you can easily manipulate the data to get the desired result. For instance in the example below I rbind additional rows to the data, where the factor levels have additional spaces. I used mtcars to get a reproducible example.

# original plot
ggplot(mtcars, aes(factor(cyl))) + geom_bar() 

# function to duplicate a factor level 
duplicate.factor.levels <- function(df, f, lvl, times=1){
  # df: data.frame
  # f: factor
  # lvl: level of factor
  # times: number of duplicates
  df[, f] <- factor(df[, f])
  for (i in 1:times){
    df.lvl <- df[df[, f]==lvl, ]
    lvl <- paste0(' ', lvl, ' ') # just adds spaces before and after 
    df.lvl[, f] <- lvl
    df <- rbind(df, df.lvl)
  } 
  return(df)
}
# duplicate cyl == 4 two more times
mtcars.2 <- duplicate.factor.levels(mtcars, 'cyl', 4, 2)
# plot (same as before with new data)
p <- ggplot(mtcars.2, aes(factor(cyl))) + geom_bar() 
# scale (add spaces to limits...)
p + scale_x_discrete(limits=c('4', '6', ' 4 ', '8', '  4  ')) 
链接地址: http://www.djcxy.com/p/30834.html

上一篇: Matlab在同一个图上绘制两个loglog轴

下一篇: 如何在R中两次(或多次)绘制相同的条形图