ggplot2 geom_bar position ="dodge"不闪避

geo*_*dex 8 r bar-chart ggplot2

我有以下数据框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
Run Code Online (Sandbox Code Playgroud)

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

    ggplot(p3, aes(x = test, y = result))+ geom_bar(position="dodge", stat="identity")
Run Code Online (Sandbox Code Playgroud)

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

Jus*_*tin 11

ggplot(p3, aes(x = test, y = result, group = result)) + 
    geom_bar(position="dodge", stat="identity")
Run Code Online (Sandbox Code Playgroud)

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

ggplot(p3, aes(x = test, y = result, color = result)) + 
    geom_bar(position="dodge", stat="identity")
Run Code Online (Sandbox Code Playgroud)

编辑评论:

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

我认为密谋:

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

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

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


geo*_*dex 1

丹尼斯·墨菲对此做出了回答:

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')
Run Code Online (Sandbox Code Playgroud)

调整变量:

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

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