首页 > 解决方案 > 如何使用ggplot2删除条形图中线型图例的默认灰色填充?

问题描述

我有一个带有两个不同变量的条形图。对于其中一个因素(gr),我在图中选择了不同的“lintype”。“gr”的图例显示了“lintype”,但填充了深灰色,我认为这令人困惑。

有谁知道如何删除填充或将其更改为白色或透明?
(我发现的所有提示仅将背景更改为图例,但不影响灰色填充)

    yval <- c(3, 7, 4, 4, 8, 9, 4, 7, 9, 6, 6, 3)
trt <- rep(c("A", "B", "C"), times=4)
gr <- rep(c(rep(("case"), times = 3), rep(("control"), times = 3)), times = 2)
var <- c(rep(("var1"), times = 6), rep(("var2"), times = 6))  
df <- data.frame(yval, device, ccgroup, var)

ggplot(data=df, aes(x=var)) +
  geom_bar( color = "black", size = 1, aes(weights = yval, fill = trt, linetype = gr) , position = "dodge")

她就是剧情

标签: rggplot2

解决方案


这可以通过例如guide_legend允许您设置图例中使用的填充颜色来实现。尝试这个:

library(ggplot2)

yval <- c(3, 7, 4, 4, 8, 9, 4, 7, 9, 6, 6, 3)
trt <- rep(c("A", "B", "C"), times=4)
gr <- rep(c(rep(("case"), times = 3), rep(("control"), times = 3)), times = 2)
var <- c(rep(("var1"), times = 6), rep(("var2"), times = 6))  
df <- data.frame(yval, trt, gr, var)

ggplot(data=df, aes(x=var)) +
  geom_bar(color = "black", size = 1, aes(weights = yval, fill = trt, linetype = gr) , position = "dodge") +
  guides(linetype = guide_legend(override.aes = list(fill = c(NA, NA))))
#> Warning: Ignoring unknown aesthetics: weights


推荐阅读