首页 > 解决方案 > 如何创建具有多个分组条形的图形?

问题描述

我正在尝试使用ggplot2多个分组条创建图表。在我的数据集中,我需要选择三列,以便根据我制作的草图对该图表进行分组:

在此处输入图像描述

代码:

library(dplyr)
library(tidyr)
library(ggplot2)

DOPTransformationsMean %>% 
      select(SPL, AddedFields, ModifiedFields, RemovedFields) %>% 
      gather(Var,Val,-SPL) %>% 
      ggplot(aes(SPL, Val, group = Var)) + 
      ylab("Quantity") +
      geom_bar(stat="identity", width = 0.3) +
      scale_fill_manual(values=c("solid", "solid", "solid")) + 
      scale_color_manual(labels = c("Added Fields", "Modified Fields", "Removed Fields"), values=c('#b30000','#00b300','#00b3b3')) + 
      theme_bw(base_size = 30) + 
      theme(plot.title = element_text(hjust = 0.5), legend.title=element_blank(),legend.position = "bottom", legend.text=element_text(size=27), legend.direction="vertical") +
      scale_y_continuous(breaks = function(x) unique(floor(pretty(seq(0, (max(x) + 1) * 1.1)))))

代码结果:

在此处输入图像描述

数据集:

SPL,AddedClasses,ModifiedClasses,RemovedClasses,AddedMethods,ModifiedMethods,RemovedMethods,AddedImports,RemovedImports,AddedFields,ModifiedFields,RemovedFields
Reminder-PL,49,76,0,99,78,1,43,0,62,0,2
Iris-PL,84,21,4,14,8,0,34,0,2,0,0

我遵循了一个类似的示例,可以生成折线图,但是通过对我的数据集进行分组,我无法对条形图进行分组。

标签: rggplot2

解决方案


您必须告诉ggplot根据aes情节部分中的组填充条形图。

DOPTransformationsMean %>% 
    select(SPL, AddedFields, ModifiedFields, RemovedFields) %>% 
    gather(Var,Val,-SPL) %>% 
    ggplot(aes(SPL, Val, group = Var, fill = Var)) + 
    ylab("Quantity") +
    geom_bar(stat="identity", width = 0.3, position = "dodge") +
    scale_fill_manual(labels = c("Added Fields", "Modified Fields", "Removed Fields"),
                      values=c('#b30000','#00b300','#00b3b3')) + 
    theme_bw(base_size = 30) + 
    theme(plot.title = element_text(hjust = 0.5), legend.title=element_blank(),
          legend.position = "bottom", legend.text=element_text(size=27), 
          legend.direction="vertical") +
    scale_y_continuous(breaks = function(x) unique(floor(pretty(seq(0, (max(x) + 1) * 1.1)))))

例子


推荐阅读