我正試圖讓我的 ggplot2 傳說很好地坐在一起。
我有一個填充圖例和一個顏色圖例,我希望它們位于繪圖底部的多行上,但顏色圖例直接在填充圖例之后繼續,而不是開始一個新列。
我在下面做了一個簡單的例子和??所需的輸出(只是用油漆制作的)來說明
library(ggplot2)
set.seed(1)
testdf <- data.frame(mon = factor(month.abb, levels = month.abb), y = rnorm(84,mean = 20, sd = 10), cat = rep(paste0("class ",letters[1:7]), each = 12))
thresholds <- data.frame(ThresholdNm = c("low","high"), ThresholdVal = c(110,150))
ggplot(testdf, aes(x = mon, y = y, fill = cat))
geom_bar(stat = "identity")
geom_hline(data = thresholds, aes(yintercept = ThresholdVal, colour = ThresholdNm))
scale_colour_manual(values = c("red","black"))
theme(legend.position = "bottom", legend.title = element_blank())
guides(fill = guide_legend(nrow=3,byrow=FALSE,order = 1),colour = guide_legend(nrow=2,byrow=FALSE,order = 2))
這就是我得到的:

但我希望的是:

由reprex 包于 2022-11-10 創建(v0.3.0)
uj5u.com熱心網友回復:
根據您的情況調整我對這篇文章的回答,您可以使用自定義鍵字形實作您想要的結果,如下所示:
- 基本上,這涉及
ThresholdVal在. 這樣做也會將專案添加到填充圖例中。fillgeom_hline - 創建一個調色板,既可用于 也可用于比例,
fill并color負責專案的正確順序。 - 撰寫自定義鍵字形函式,該函式根據顏色值在用于條的鍵字形和用于條形的鍵字形之間切換
geom_hline - 洗掉顏色圖例。
- 使用主題選項在所有圖例鍵周圍設定邊框,包括用于 hlines 的鍵。
library(ggplot2)
nclass <- nlevels(factor(testdf$cat))
pal <- c(scales::hue_pal()(nclass), "red", "black")
names(pal) <- c(levels(factor(testdf$cat)), "high", "low")
draw_key_cust <- function(data, params, size) {
if (data$fill %in% c("red", "black")) {
data$colour <- data$fill
data$fill <- NA
draw_key_path(data, params, size)
} else {
GeomCol$draw_key(data, params, size)
}
}
ggplot(testdf, aes(x = mon, y = y, fill = cat))
geom_bar(stat = "identity", key_glyph = "cust")
geom_hline(data = thresholds, aes(yintercept = ThresholdVal, colour = ThresholdNm, fill = ThresholdNm))
scale_fill_manual(values = pal, aesthetics = c("fill", "color"))
theme(legend.position = "bottom", legend.title = element_blank(),
legend.key = element_rect(linewidth = .25 * .pt, color = "white"))
guides(fill = guide_legend(nrow = 3, byrow = FALSE, order = 1), colour = "none")
#> Warning in geom_hline(data = thresholds, aes(yintercept = ThresholdVal, :
#> Ignoring unknown aesthetics: fill

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/531708.html
標籤:rggplot2传奇
下一篇:如何在R中制作重疊的餅圖?
