r - 条形图条走向错误的方向

标签 r ggplot2

我是一名正在学习 R 的生物学研究生。我希望有人可以帮助我让条形图在相反的方向水平移动(蓝色部分应该从 0 开始,红色部分应该从 100 开始)。

带有错误方向的条形图

enter image description here

这是数据

my_species <- c('apomict_2-17-17_compreh', 'apomict_2-17-17_compreh', 'apomict_2-17-17_compreh', 'apomict_2-17-17_compreh', 'parthenogen_2-17-17_compreh', 'parthenogen_2-17-17_compreh', 'parthenogen_2-17-17_compreh', 'parthenogen_2-17-17_compreh', 'sexual_2-9-17', 'sexual_2-9-17', 'sexual_2-9-17', 'sexual_2-9-17')
my_species <- factor(my_species)
my_species <- factor(my_species,levels(my_species)[c(length(levels(my_species)):1)]) # reorder your species here just by changing the values in the vector :
my_percentage <- c(36.3, 56.3, 2.6, 4.8, 42.2, 50.6, 2.4, 4.8, 56.0, 19.9, 6.7, 17.4)
my_values <- c(522, 811, 38, 69, 608, 729, 35, 68, 806, 286, 96, 252)
category <- c(rep(c("S","D","F","M"),c(1)))
category <-factor(category)
category = factor(category,levels(category)[c(4,1,2,3)])
df = data.frame(my_species,my_percentage,my_values,category)

代码如下:

# Load the required libraries
library(ggplot2)
library("grid")

# !!! CONFIGURE YOUR PLOT HERE !!! 
# Output
#my_output <- paste("/home/loki/","busco_figure.png",sep="/") 
my_width <- 20
my_height <- 15
my_unit <- "cm"

# Colors
my_colors <- c("#56B4E9", "#3492C7", "#F0E442", "#F04442")
# Bar height ratio
my_bar_height <- 0.75

# Legend
my_title <- "BUSCO Assessment Results"

# Font
my_family <- "sans"
my_size_ratio <- 1


# Code to produce the graph
labsize = 1
if (length(levels(my_species)) > 10){
 labsize = 0.66
}
print("Plotting the figure ...")


figure <- ggplot() +       
  geom_bar(aes(y = my_percentage, x = my_species, fill = category), data = df, stat="identity", width=my_bar_height) + 
  coord_flip() + 
  theme_gray(base_size = 8) + 
  #scale_y_continuous(labels = c("100","80","60","40","20","0"), breaks = c(100,80,60,40,20,0)) + 
  scale_y_continuous(labels = c("100","80","60","40","20","0"), breaks = c(100,80,60,40,20,0)) +
  #scale_y_continuous(labels = c("100","80","60","40","20","0"), breaks = c(0,20,40,60,80,100)) +
  scale_fill_manual(values = my_colors,labels =c(" Complete (C) and single-copy (S)  ",
                                                 " Complete (C) and duplicated (D)",
                                                 " Fragmented (F)  ",
                                                 " Missing (M)")) +   
  ggtitle(my_title) + 
  xlab("") + 
  ylab("\n%BUSCOs") + 

  theme(plot.title = element_text(family=my_family, colour = "black", size = rel(2.2)*my_size_ratio, face = "bold")) + 
  theme(legend.position="top",legend.title = element_blank()) + 
  theme(legend.text = element_text(family=my_family, size = rel(1.2)*my_size_ratio)) + 
  theme(panel.background = element_rect(color="#FFFFFF", fill="white")) + 
  theme(panel.grid.minor = element_blank()) + 
  theme(panel.grid.major = element_blank()) +
  theme(axis.text.y = element_text(family=my_family, colour = "black", size = rel(1.66)*my_size_ratio)) + 
  theme(axis.text.x = element_text(family=my_family, colour = "black", size = rel(1.66)*my_size_ratio)) + 
  theme(axis.line = element_line(size=1*my_size_ratio, colour = "black")) + 
  theme(axis.ticks.length = unit(.85, "cm")) + 
  theme(axis.ticks.y = element_line(colour="white", size = 0)) + 
  theme(axis.ticks.x = element_line(colour="#222222")) + 
  theme(axis.ticks.length = unit(0.4, "cm")) + 
  theme(axis.title.x = element_text(family=my_family, size=rel(1.2)*my_size_ratio)) + 

  guides(fill = guide_legend(override.aes = list(colour = NULL))) +
  guides(fill=guide_legend(nrow=2,byrow=TRUE))

  for(i in rev(c(1:length(levels(my_species))))){
    detailed_values <- my_values[my_species==my_species[my_species==levels(my_species)[i]]]
    total_buscos <- sum(detailed_values)
    figure <- figure + 
    annotate("text", label=paste("C:", detailed_values[1] + detailed_values[2], " [S:", detailed_values[1], ", D:", detailed_values[2], "], F:", detailed_values[3], ", M:", detailed_values[4], ", n:", total_buscos, sep=""), 
             y=3, x = i, size = labsize*4*my_size_ratio, colour = "black", hjust=0, family=my_family)
  }

my_output="~/temp.png"
ggsave(figure, file=my_output, width = my_width, height = my_height, unit = my_unit)
print("Done")

最佳答案

?position_stack:

position_fill() and position_stack() automatically stack values in reverse order of the group aesthetic, which for bar charts is usually defined by the fill aesthetic (the default group aesthetic is formed by the combination of all discrete aesthetics except for x and y). This default ensures that bar colours align with the default legend.

为了改变堆叠方向,你只需要添加position = position_stack(reverse = TRUE)geom_bar:

figure <- ggplot() +       
    geom_bar(
        aes(y = my_percentage, x = my_species, fill = category),
        data = df, stat="identity", width=my_bar_height,
        position = position_stack(reverse = TRUE)) + 
    coord_flip() + 
...

enter image description here

如果您不想使用 position_stack,则必须更改因子级别,并且您还必须设置填充颜色中断以保持相同的图例顺序。

关于r - 条形图条走向错误的方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43010711/

相关文章:

R:使用 ggplot 找不到对象

r - 如何阻止pdf中的bookdown表格 float 到页面底部?

r - 将定制的 ggpairs() 绘图对象累积到列表对象中

r - 使用 R 计算面板数据中自上次事件以来的运行次数

r - 如何将 data.frame 转换为树状结构对象,例如树状图

r - facet_wrap(ggplot2)中的多个标题

r - ggplot2:stat_smooth用于使用facet_wrap返回 'full'或 'subset' glm模型的逻辑结果

r - 条形图 ggplot : conflict between values on bar and x axis label

r - ggplot2 在 .elements_tree 之外创建一个新的主题元素

r - ggplot2 命名空间问题