簡體   English   中英

如何在ggplot2中的單個方面注釋文本

[英]How to annotate text on individual facet in ggplot2

這個問題是對以下問題的后續: Annotating text on individual facet in ggplot2

我正在嘗試接受的答案中提供的代碼,但得到的結果與提供的結果奇怪地不同。 當然,帖子較舊,我使用的是 R 3.5.3 和 ggplot2 3.1.0,但我得到的似乎沒有意義。

library(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p <- p + facet_grid(. ~ cyl)

#below is how the original post created a dataframe for the text annotation
#this will produce an extra facet in the plot for reasons I don't know
ann_text <- data.frame(mpg = 15,wt = 5,lab = "Text",cyl = factor(8,levels = c("4","6","8")))

p+geom_text(data = ann_text,label = "Text")

這是鏈接問題中已接受答案的代碼。 對我來說,它產生了帶有額外方面的下圖(即,似乎已將 3 的附加分類變量添加到 cyl)

https://github.com/RamenZzz/hello-world/blob/master/Rplot09b.jpeg?raw=true

#below is an alternative version that produces the correct plot, that is,
#without any extra facets.
ann_text_alternate <- data.frame(mpg = 15,wt = 5,lab = "Text",cyl = 8)

p+geom_text(data = ann_text_alternate,label = "Text")

這給了我正確的圖表:

https://raw.githubusercontent.com/RamenZzz/hello-world/master/Rplot09a.jpeg

有人有任何解釋嗎?

正在發生的事情是一個因素問題。
首先,您按cyl面,這是數據集mtcars一列。 這是一個采用 3 個不同值的"numeric"類的對象。

unique(mtcars$cyl)
#[1] 6 4 8

然后,您創建一個新數據集,即數據ann_text 但是您將cyl定義為類"factor"的對象。 可以通過str看到此列中的內容。

str(ann_text)
#'data.frame':  1 obs. of  4 variables:
# $ mpg: num 15
# $ wt : num 5
# $ lab: Factor w/ 1 level "Text": 1
# $ cyl: Factor w/ 3 levels "4","6","8": 3

R 將因子編碼為從1開始的整數,級別"8"是級別編號3
因此,當您組合兩個數據集時, cyl4 個值,原始數字468加上新數字3 因此,額外的方面。

這也是該解決方案有效的原因,在數據幀中ann_text_alternatecyl是一個數值變量,采用已經存在的值之一。

使其工作的另一種方法是在刻面時強制cyl為因子。 注意

levels(factor(mtcars$cyl))
#[1] "4" "6" "8"

並且新的數據幀ann_text不再有第 4 級。 開始按照問題繪制圖形

p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p <- p + facet_grid(. ~ factor(cyl))

並添加文本。

p + geom_text(data = ann_text, label = "Text")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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