更改ggplot2中的单个网格线颜色?

时间:2019-02-22 16:59:45

标签: r ggplot2

是否可以控制ggplots中面板网格中特定线条的颜色?我想使用“ geom_hline”在“ y”轴上用“装饰性”线表示0。您可以从下面的代码和图中看到,仅添加geom_hline即可保持灰色网格线。我希望与y轴相交的线是透明的,而其余网格线保持为灰色。

library(ggplot2)
ggplot(data = NULL)+
  geom_hline(yintercept = 0, linetype = 4, size = 2)+
  theme_minimal()+
  theme(panel.grid = element_line(size = 2))

enter image description here

1 个答案:

答案 0 :(得分:1)

由于ggplot图层是按照接收顺序绘制的,因此您可以在虚线图层下方绘制一个geom_hline(与网格线大小相同或更大),使其颜色与背景填充,它将遮挡网格线。

在一个简单的情况下,您知道背景颜色(在这种情况下为白色):

library(ggplot2)
ggplot(data = NULL) +
  geom_hline(yintercept = 0, size = 2, color = "white") +
  geom_hline(yintercept = 0, linetype = 4, size = 2) +
  theme_minimal() +
  theme(panel.grid = element_line(size = 2))

要使其更具动态性并与主题匹配,请填充​​主题的情节背景,并将其设置为颜色:

ggplot(data = NULL) +
  geom_hline(yintercept = 0, size = 2, 
             color = theme_dark()$panel.background$fill) +
  geom_hline(yintercept = 0, linetype = 4, size = 2) +
  theme_dark() +
  theme(panel.grid = element_line(size = 2))