[英]In a ggplot2 geom_tile plot, is it possible to dodge the positions of tiles?
我正在嘗試制作一個條形圖,其中條形根據第三個變量垂直消失,並且我正在使用geom_tile來啟用此功能。 但是,對於x軸上的給定類別,我有多個條形,並且我想避開它們的位置,以便在不重疊的條形組中將相同的x值放在一起。
是否可以在geom_tile
使用position='dodge'
或類似geom_tile
,如果這樣,我的語法有什么問題?
a <- data.frame(x = factor(c(rep('a',5), rep('a',5), rep('b',5), rep('c',5))),
y = c(1:5, 1:5, 1:5, 1:5),
z = c(5:1, c(5,4,4,4,1), 5:1, 5:1)
)
ggplot(a, aes(x = x, y = y, group = x)) +
geom_tile(aes(alpha = z, fill = x, width = 1),
position = 'dodge')
示例數據幀a
如下所示:
x y z
1 a 1 5
2 a 2 4
3 a 3 3
4 a 4 2
5 a 5 1
6 a 1 5
7 a 2 4
8 a 3 4
9 a 4 4
10 a 5 1
11 b 1 5
12 b 2 4
13 b 3 3
14 b 4 2
15 b 5 1
16 c 1 5
17 c 2 4
18 c 3 3
19 c 4 2
20 c 5 1
...並且當前代碼生成的圖在x值之間沒有間隙,並且其中x是a的兩個值在另一個的頂部繪制:
我希望將x為'a'的兩個條形繪制為單獨的條形。
這是我希望結果看起來像的模型。 數據對於任一a列都不正確,但是在x軸上顯示了所需的分組:
編輯2
為了獲得理想的效果,請使用geom_bar()
但請確保更改y
數據以指示鋼筋高度,在這種情況下為1。原因是鋼筋堆疊在一起,因此無需指定y軸位置 ,而是指定height 。
嘗試這個:
library(ggplot2)
a <- data.frame(x = factor(c(rep('a',5), rep('a',5), rep('b',5), rep('c',5))),
y = 1,
z = c(5:1, c(5,4,4,4,1), 5:1, 5:1)
)
a$bar <- rep(1:4, each=5)
ggplot(a, aes(x = factor(bar), y=y, fill=x, alpha=z)) +
geom_bar(stat="identity") +
facet_grid(~x, space="free", scale="free")
您應該得到:
編輯1
您可以通過以下方式接近您的描述:
例如:
a$bar <- rep(1:4, each=5)
ggplot(a, aes(x = factor(bar), y = y, fill=x, alpha=z)) +
geom_bar(stat="identity", position="dodge") +
facet_grid(~x, space="free", scale="free")
原版的
您可以通過使用stat="identity"
來使用geom_bar()
:
ggplot(a, aes(x = x, y = y, fill=x, alpha=z)) +
geom_bar(stat="identity", position="dodge")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.