在 ggplot2 中,我想將 boxplot dotplot 并排繪制為附加影像。但是代碼無法作業,有人可以幫忙嗎?此代碼來自“R 圖形食譜”。謝謝!
library(gcookbook)
library(tidyverse)
ggplot(heightweight,aes(x=sex,y=heightIn ))
geom_boxplot(aes(x=as.numeric(sex) 0.2),group=sex)
geom_dotplot(aes(x=as.numeric(sex)-0.2),group=sex,
binaxis = "y",stackdir = 'center',
binwidth = 0.5)

uj5u.com熱心網友回復:
這是一個非常有趣的問題。OP 正在尋求沿 x 軸躲避幾何圖形,這通常并不難做到。這里的困難在于您正在使用不同的 geoms來躲避相同的資料。
您可以做的是使用一些巧妙的格式化、映射和分面來重新創建 OP 顯示的繪圖型別的示例。對于此示例解決方案,我使用的是內置資料集iris. 將來,OP,請務必使用內置資料集、您的資料或您的資料樣本提供可重現的示例。
這是在下面的箱形圖頂部顯示點圖的基本圖 - 我將嘗試拆分右側的箱線圖和左側的點圖。
ggplot(iris, aes(x=Species, y=Sepal.Width))
geom_boxplot(width=0.3)
geom_dotplot(binaxis = 'y', binwidth=0.04, stackdir = "center")

閃避是根據資料框中特定列的值在特定幾何中分割美學的行為。基本上,這意味著您可以有兩個相鄰的箱線圖、兩個點等 - 根據資料中另一列的值,每個箱線圖的顏色或表示方式不同。我們不能使用 dodging 將 boxplot 與 dotplot 一起移動,因為dodging 僅適用于同一個 geom。對于相同的 x 指定值,您可以有兩個相鄰的箱線圖...但不能有箱線圖和點圖。
這里的解決方案是單獨繪制我們的幾何圖形 - 有效地“手動”進行躲避。我無法在特定的 x 值(如“x 右”與“x 左”)內指定一個段,所以在我看來,讓這個作業的唯一方法是使用 faceting 在資料集中創建實際的 x 位置,并且將使用 x 軸在圖中指定閃避的位置資訊。這意味著 x 中的每個值(在此示例中為 each Species)將是一種迷你圖 - 左側為點圖,右側為箱線圖。
這是代碼和結果:
ggplot(iris, aes(x=positional, y=Sepal.Width))
geom_dotplot(aes(x = "1"), binaxis="y", binwidth=0.04, stackdir="center")
geom_boxplot(aes(x = "2"), width=0.6)
facet_wrap(~Species, strip.position = "bottom")
theme(
# panel.spacing.x = unit(0, "npc"),
strip.background = element_blank(),
strip.text = element_text(size=12),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.title.x = element_blank()
)

What's going on here? Well, you'll notice that I'm mapping x to a new "column" in the dataset called "positional". This column does not exist in the dataset, so I define it separately for geom_boxplot() and geom_dotplot(). You have to do this in aes(), since it's required for mapping, but if you map in aes() to a constant value, the plot will be created as if every observation is set at that value. This is useful, because this creates our dotplot on the left (where positional == "1" and our boxplot on the right (where positional == "2").
其余代碼只是主題內容和創建方面。請注意,我使用strip.placement將分面標簽移動到底部,然后洗掉所有其他軸元素,以便我們的分面標簽作為新的軸標簽。
最后,您可以保持構面之間的間距(我有點喜歡它),或者您也可以通過使用另一個theme()元素來洗掉它。添加theme(panel.spacing = unit(0, "npc"))給你:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/420831.html
標籤:
