如何在ggplot中透明应用legend.key背景?

时间:2018-11-04 04:39:15

标签: r ggplot2

我在ggplot2软件包中使用# BaseRequestHandler __init__ must be the last statement as all request processing happens in this method socketserver.BaseRequestHandler.__init__(self, request, client_address, server) 数据来测试绘图参数。我发现lengend.key背景色(右上,标签为车辆型号)的颜色可以更改为除透明或白色以外的任何其他颜色。如何将lengend键的背景默认灰色更改为透明?

mpg

this article

1 个答案:

答案 0 :(得分:2)

您需要添加se = FALSE或删除stat_smooth(method = "loess")才能删除vehicle model图例键中的灰色填充背景。

library(ggplot2)

p <- ggplot(data = mpg, mapping = aes(x = cty, y = hwy, colour = class)) +
  geom_point(aes(size = displ), alpha = 0.5) +
  stat_smooth(method = "loess", se = FALSE) + # Add se = FALSE
  scale_size_continuous(range = c(4, 10)) +
  facet_wrap(~year, ncol = 2) +
  labs(
    x = "distance per gallon in city", y = "distance per gallon in highway",
    title = "fuel consumption and model", size = "displacement", colour = "vehicle model"
  )

p + 
  theme(
    plot.background = element_blank(),
    panel.background = element_rect(fill = "transparent", colour = "gray"),
    panel.border = element_rect(fill = "transparent", colour = "black"),
    axis.text = element_text(color = "black"),
    panel.grid.major = element_line(colour = "grey", linetype = "dashed"),
    strip.background = element_blank(),
    panel.spacing.x = unit(4, "mm"),
    legend.box.background = element_rect(fill = "blue", colour = "transparent"),
    legend.key = element_rect(fill = "transparent", colour = "transparent")
  )

p +
  theme(
    plot.background = element_rect(fill = "transparent", colour = "transparent"),
    panel.background = element_rect(fill = "transparent", colour = "gray"),
    panel.border = element_rect(fill = "transparent", colour = "black"),
    axis.text = element_text(color = "black"),
    panel.grid.major = element_line(colour = "grey", linetype = "dashed"),
    strip.background = element_rect(fill = "transparent", colour = "transparent"),
    panel.spacing.x = unit(4, "mm"),
    legend.background = element_blank(),
    legend.box.background = element_blank(),
    legend.key = element_blank()
  )

reprex package(v0.2.1.9000)于2018-11-03创建