ggplot2 geom_bar position =“dodge”不闪避

时间:2012-06-12 22:29:22

标签: r ggplot2 bar-chart

我的数据框p3如下:

         test     result
    1      1    26.87778
    2      1    24.52598
    3      1    24.02202
    4      1    20.32632
    5      1    22.00618
    6      2    19.84013
    7      2    19.68983
    8      2    19.84013
    9      2    19.23892
    10     2    19.23892
    11     3    34.36430
    12     3    33.28196
    13     3    33.82313
    14     3    33.82313
    15     3    32.47020
    16     4    25.55169
    17     4    26.90442
    18     4    25.40138
    19     4    24.19895
    20     4    25.85230
    21     4    25.70199
    22     4    24.95047
    23     5    18.64646
    24     5    18.64646
    25     5    17.80653
    26     5    18.64646
    27     5    18.31049

我正在尝试使用代码制作带有躲闪结果的条形图:

    ggplot(p3, aes(x = test, y = result))+ geom_bar(position="dodge", stat="identity")

但它根本不起作用。我不明白为什么它不起作用,因为我以前使用相同的代码并且它起作用。

2 个答案:

答案 0 :(得分:11)

ggplot(p3, aes(x = test, y = result, group = result)) + 
    geom_bar(position="dodge", stat="identity")

如果将group参数更改为color,您可以看到发生了什么。

ggplot(p3, aes(x = test, y = result, color = result)) + 
    geom_bar(position="dodge", stat="identity")

编辑评论:

看起来有奇数组,因为有。第4组在您提供的数据中包含7个元素。第3组有5个,但其中2个是相同的。该图正确显示高度,并将元素组合在一起。就像你在每个组中调用unique一样。

我认为密谋:

ggplot(p3, aes(x=test, y=result, group=result, color=result)) + 
  geom_bar(position='dodge', stat='identity')

很好地展示了这一点。至于每个组有5个元素,情况并非如此。第4组有7.要查看您所描述的内容,您可以执行以下操作:

ggplot(p3, aes(x=as.integer(row.names(p3)), y=result, fill=factor(test))) +   
  geom_bar(position='dodge', stat='identity')

答案 1 :(得分:0)

Dennis Murphy回答:

p3$test <- factor(p3$test)
p3$fac <- factor(unlist(sapply(as.vector(table(p3$test)), seq_len)))
ggplot(p3, aes(x = test, y = result, fill = fac)) + 
      geom_bar(position = 'dodge', stat = 'identity')

调整变量:

ggplot(p3, aes(x = test, y = result, color = fac, fill = test)) +
    geom_bar(position = 'dodge', stat = 'identity', linetype = 0)

我几乎得到了我想要的东西,除了颜色(轮廓)应该是相同的。但它足够接近。

相关问题