[英]How to remove boxes around ggplot2 legend labels
我有一個折線圖,在數據的第一和第三四分之一之間有一個色帶。 當我使用 plot 和 ggplot2 的數據時,我在標簽周圍得到了方框,無論我嘗試什么(即主題(legend.background=element_blank())或指南(guides_legend)覆蓋)。 dataframe這是我的數據集和代碼的第一行:
mutate(code_range = fct_reorder2(code_range, year, order)) %>%
ggplot(aes(x=year, y=value, group=code_range, color=code_range)) +
geom_ribbon(aes(ymin = min_range,
ymax = max_range), fill = "grey70", alpha=0.1) +
geom_line(size=1) +
labs(title="Title",
subtitle=paste0("subtitle"),
x="",y="",
caption="Source") +
scale_colour_manual(values = c("min" = "#878787", "q1" = "#B5B5B5", "median" = "#27408B",
"q3" = "#B5B5B5", "max" = "#878787")) +
scale_fill_manual(values = c("min" = "#FFFFFF", "q1" = "#B5B5B5", "median" = "#27408B",
"q3" = "#B5B5B5", "max" = "#878787")) +
theme_opts +
theme(legend.title = element_blank(),
legend.position = "bottom") +
theme(legend.background=element_blank())
plot
有人知道如何刪除這些框的解決方案嗎?
圖例鍵周圍的框反映了geom_ribbon
。 要刪除它們,您可以將show.legend=FALSE
添加到geom_ribbon
。
使用一些假的示例數據:
library(ggplot2)
df <- data.frame(
year = 2005:2020,
value = 1:16,
min_range = 1:16 - 1,
max_range = 1:16 + 1
)
base <- ggplot(df, aes(year, value, color = "median")) +
geom_line() +
scale_colour_manual(values = c(
"min" = "#878787", "q1" = "#B5B5B5", "median" = "#27408B",
"q3" = "#B5B5B5", "max" = "#878787"
))
首先復制您的問題:
base +
geom_ribbon(aes(ymin = min_range, ymax = max_range), fill = "grey70", alpha = 0.1)
第二個使用show.legend = FALSE
:
base +
geom_ribbon(aes(ymin = min_range, ymax = max_range), fill = "grey70", alpha = 0.1, show.legend = FALSE)
另一種選擇是將顏色美學僅移動到 geom_line
library(ggplot2)
p <- ggplot(iris, aes(Sepal.Length, Petal.Width, color = Species)) +
geom_smooth()
df_p <- layer_data(p)
#> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'
## something similar to your plot
ggplot(df_p, aes(color = as.character(group))) +
geom_ribbon(aes(x = x, ymin = ymin, ymax = ymax)) +
geom_line(aes(x, y))
## change the location of your color aesthetic to geom_line only
## you need to add a grouping aesthetic into the ribbon call
ggplot(df_p) +
geom_ribbon(aes(x = x, ymin = ymin, ymax = ymax, group = as.character(group))) +
geom_line(aes(x, y, color = as.character(group)))
創建於 2023-01-02,使用reprex v2.0.2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.