簡體   English   中英

在ggplot2 geom_tile圖中,是否可以躲避圖塊的位置?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM