[英]ggplot2: geom_bar with group, position_dodge and fill
[英]ggplot2 geom_bar position = “dodge” does not dodge
我有以下數據框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')
丹尼斯墨菲回答了這個問題:
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)
我幾乎得到了我想要的東西,除了顏色(輪廓)應該是相同的。 但它足夠接近。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.