假設我在下面ggplot
library(ggplot2)
library(ggnewscale)
data =
structure(list(grp1 = c("X", "X", "X", "X", "Y", "Y", "Y", "Y"
), grp2 = c("A", "B", "C", "D", "A", "B", "C", "D"), val = c(1,
2, 3, 4, 3, 4, 5, 6)), row.names = c(NA, -8L), class = "data.frame")
col_define = c('red', 'orange', 'blue', 'lightblue')
names(col_define) = c('A', 'B', 'C', 'D')
ggplot(data, aes(x = grp1, group = grp2, y = val))
geom_col(aes(fill = grp2))
scale_fill_manual(values = col_define, breaks = c("A", "B"), name = "1")
new_scale_fill()
geom_col(aes(fill = grp2))
scale_fill_manual(values = col_define, breaks = c("C", "D"), name = "2")
theme(legend.position="top", legend.direction = 'vertical',
legend.box.margin = margin(),
legend.box.background = element_rect(fill = alpha('#e5e5e5', 0.60), size = 0.1, linetype = 'solid', color = '#333333'))
正如我們所看到的,我嘗試使用在我的繪圖中添加背景透明度element_rect(fill = alpha('#e5e5e5', 0.60),但是不起作用。有沒有其他方法可以在這個情節的背景中添加透明度?
我也想更改圖例標簽中2, 1的順序,例如1, 2。基本上我想應用一些自定義排序,以防有很多級別。
任何指標都會非常有幫助。
uj5u.com熱心網友回復:
傳奇背景總是有點棘手。因為我們必須處理多個元素。此外,我不是 100% 確定添加背景透明度是什么意思。但我做的第一件事是洗掉顏色和填充legend.background,即圍繞每個圖例繪制的框(而legend.box.background圍繞所有圖例繪制的框的背景(;順便說一句:還有單個圖例鍵的背景這是通過legend.key. :D 設定的)。
簡單的部分是圖例的順序,可以通過 的order引數設定guide_legend。
library(ggplot2)
library(ggnewscale)
data <-
structure(list(grp1 = c("X", "X", "X", "X", "Y", "Y", "Y", "Y"), grp2 = c("A", "B", "C", "D", "A", "B", "C", "D"), val = c(
1,
2, 3, 4, 3, 4, 5, 6
)), row.names = c(NA, -8L), class = "data.frame")
col_define <- c("red", "orange", "blue", "lightblue")
names(col_define) <- c("A", "B", "C", "D")
ggplot(data, aes(x = grp1, group = grp2, y = val))
geom_col(aes(fill = grp2))
scale_fill_manual(values = col_define, breaks = c("A", "B"), name = "1", guide = guide_legend(order = 2))
new_scale_fill()
geom_col(aes(fill = grp2))
scale_fill_manual(values = col_define, breaks = c("C", "D"), name = "2", guide = guide_legend(order = 1))
theme(
legend.position = "top",
legend.direction = "vertical",
legend.box.margin = margin(),
legend.background = element_rect(color = NA, fill = NA),
legend.box.background = element_rect(
fill = alpha('#e5e5e5', .6), size = 0.1, linetype = "solid", color = "#333333"
)
)

uj5u.com熱心網友回復:
這是一個替代方案:
ggplot(data, aes(x = grp1, group = grp2, y = val))
geom_col(aes(fill = grp2))
scale_fill_manual(values = col_define, breaks = c("B", "A"), name = "1")
new_scale_fill()
geom_col(aes(fill = grp2))
scale_fill_manual(values = col_define, breaks = c("C", "D"), name = "2")
theme(legend.position="top", legend.direction = 'vertical',
legend.background = element_rect(fill="gray",
size=1, linetype="solid",
color ="gray"))

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/520915.html
