ggplot2中不同的分组条形图

时间:2016-08-10 04:15:08

标签: r ggplot2

使用以下数据集:

GPU_Config,Job_Num,File_Amount,Seconds
0_1_2_3,4,1400,44015.833
0_1_2_3,8,1400,35509
0_1_2_3,12,1400,40544.75
02_13,2,1400,50209.5
02_13,4,1400,39379
02_13,6,1400,39507
02_13,8,1400,39871
02_13,10,1400,42823.75
02_13,12,1400,46727

有没有办法用这组特定的数据制作这种条形图?:

enter image description here

我尝试过这样的事情:

ggplot(jobtest, aes(x = GPU_Config, y = Seconds, fill = GPU_Config, color = GPU_Config)) + geom_bar(position = position_dodge(.908), stat = "identity")

有趣的是,将position设置为position_jitter()或position_jitterdodge()确实会开始将条形图分开一点,但只是做闪避根本不做任何事情。

但它们似乎不起作用。关于分组条形图的许多其他R帖都略有不同且难以理解。无论如何我不是R专家。有人可以帮忙吗?

修改

更多新信息曝光。通过在CSV的末尾添加“类型”列来编辑数据,将每一行设置为不同的字母,A-I,并将“填充”设置为等于“类型”,但显然所有条形都是不同的颜色。有没有办法将它们分成相同的颜色?

新数据:

GPU_Config,Job_Num,Tiff_Amount,Seconds,Type
0_1_2_3,4,1400,44015.833,a
0_1_2_3,8,1400,35509,b
0_1_2_3,12,1400,40544.75,c
02_13,2,1400,50209.5,d
02_13,4,1400,39379,e
02_13,6,1400,39507,f
02_13,8,1400,39871,g
02_13,10,1400,42823.75,h
02_13,12,1400,46727,i

新守则:

ggplot(jobtest, aes(x = GPU_Config, y = Seconds, fill = Type, color = "Black")) + geom_bar(position = position_dodge(), stat = "identity")

enter image description here

2 个答案:

答案 0 :(得分:4)

这样的东西?

text <- 
"GPU_Config,Job_Num,File_Amount,Seconds
0_1_2_3,4,1400,44015.833
0_1_2_3,8,1400,35509
0_1_2_3,12,1400,40544.75
02_13,2,1400,50209.5
02_13,4,1400,39379
02_13,6,1400,39507
02_13,8,1400,39871
02_13,10,1400,42823.75
02_13,12,1400,46727"

df <- read.table(textConnection(text), sep = ",", header = TRUE)

df$type <- as.factor(1:nrow(df))

library(ggplot2)
  ggplot(df) +
  geom_bar(aes(x = type, y = Seconds, fill = GPU_Config), 
  stat = "identity", position = "dodge") +
  facet_wrap(~ GPU_Config, scales = 'free_x')

enter image description here

如果您不希望切面分离/想要X轴上的GPU_config,您可以隐藏颜色指南并手动指定颜色

ggplot(df) +
  geom_bar(aes(x = GPU_Config, y = Seconds, fill = type), 
  colour = 'black', stat = "identity", position = "dodge") +
  scale_fill_manual(guide = FALSE,
                    values=c("red", "red", "red", 
                            'blue', 'blue', 'blue', 'blue', 'blue', 'blue')
  )

enter image description here

答案 1 :(得分:1)

这是你要找的吗?

    txt <- "GPU_Config,Job_Num,File_Amount,Seconds
    0_1_2_3,4,1400,44015.833
    0_1_2_3,8,1400,35509
    0_1_2_3,12,1400,40544.75
    02_13,2,1400,50209.5
    02_13,4,1400,39379
    02_13,6,1400,39507
    02_13,8,1400,39871
    02_13,10,1400,42823.75
    02_13,12,1400,46727"

    df1 <- read.table(textConnection(txt), sep = ",", header = TRUE)

    library(ggplot2)
    g + geom_bar(aes(fill = Job_Num), stat = "identity", position = "dodge") + 
      theme_bw() +
      facet_grid( . ~ GPU_Config)

Result