我在下面有数据帧 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")
但它根本不起作用。我不明白为什么它不起作用,因为我之前使用相同的代码并且它有效。
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')
丹尼斯·墨菲(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)
我几乎得到了我想要的,除了颜色(轮廓)应该相同。 但它足够接近。