ggplot2中的geom_bar position = "dodge"无法正确分开柱状图。

10

我有以下数据框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个回答

12
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')

没错,我本来想指出如果没有像fillcolour这样的自然分组美学,dodging就不会有多大作用。 - joran
@Joran 很好的观点。然而,即使在 aes 中添加了 fillcolourposition='dodge' 也不会发生。你需要使用 group,这样 dodge 就知道它要躲避什么东西。stat='identity' 不像其他统计量那样提供自动分组。 - Justin
我不确定你所说的“dodging together”是什么意思...你所描述的正是position='dodge'的作用。你是不是指的是position='stack' - Justin
@Justin 我的意思是test1应该并排放置,然后是test2等等...每个测试应该有5个项目。从你的代码生成的图表元素数量不均匀,这是不应该的。 - geodex
@geodex 看看我的编辑。但是图表确切地显示了每个组中元素的数量。 - Justin
显示剩余2条评论

1
这个问题由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)

我差不多得到了想要的,只是颜色(轮廓)应该是一样的,但已经足够接近了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接