簡體   English   中英

將水平矩形添加到 ggplot2 中的分類箱線圖

[英]Add horizontal rectangle to categorical boxplot in ggplot2

我想在繪圖后面(或在不透明度上方)制作一個帶有水平矩形的箱線圖。 我不確定如何使用分類 x 軸值執行此操作並強制它擴展繪圖區域的整個寬度。 這個答案很有幫助,但我不確定如何將矩形擴展到繪圖區域的邊緣。

假設我們想要在 3000 美元到 5000 美元之間的diamonds切割上制作一個矩形。 我已經嘗試了下面的代碼,但它沒有延伸到情節的邊緣。

rectangle <- data.frame(x = c("Fair","Good","Very good", "Premium", "Ideal"), 
                    lower = rep(3000, 5),
                    upper = rep(5000, 5))
ggplot() +
  geom_boxplot(data=diamonds, aes(x=cut, y=price)) +
  geom_rect(data=rectangle, aes(xmin="Fair", xmax="Ideal", 
                                ymin=lower, ymax=upper), alpha=0.1)

輸出

帶矩形的箱線圖

要使矩形到達面板邊緣,您可以將限制設置為 +/-Inf。

同樣對於像這樣的單個矩形(並且沒有映射任何美學),可能值得只使用annotate

annotate("rect", xmin=-Inf, xmax=Inf, ymin=3000, ymax=5000, alpha=0.4)

但為了完整geom_rect ,您仍然可以使用geom_rect調用

geom_rect(aes(xmin=-Inf, xmax=Inf, ymin=3000, ymax=5000), alpha=0.4)

您可以通過更改幾何圖形的順序來移動箱線圖后面的矩形。

ggplot(diamonds, aes(x=cut, y=price)) +
    geom_blank() +
    annotate("rect", xmin=-Inf, xmax=Inf, ymin=3000, ymax=5000) +
    geom_boxplot()

暫無
暫無

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

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