ggplot2:情节和图例中用白色填充的线+点?

ggplot2: lines + points with white fill in plot and legend?

我想用 ggplot2 包创建一个绘图,它结合了线和点。根据组指示器,点应具有颜色和形状。应创建图例,根据绘图显示颜色和形状。

这部分工作正常。然而,所有点都应该有一个白色填充,我找不到合适的代码。

google 搜索建议使用 fill = "white",但这不起作用。

考虑以下示例数据和绘图:

library("ggplot2")

# Example data
df <- data.frame(y = 1:100,
                 x = 1:100,
                 group = as.factor(c(rep(1, 33), rep(2, 33), rep(3, 34))))

# Create plot --> fill = "white" doesnt work
ggplot(df, aes(x = x, y = y)) + 
  geom_line(aes(colour = factor(group, labels = c("a", "b", "c")))) +
  geom_point(aes(colour = factor(group, labels = c("a", "b", "c")),
                 shape = factor(group, labels = c("a", "b", "c"))),
             fill = "white") +              ##### This line is not working #####
  theme(legend.title = element_blank())

问题:如何用白色填充该图的点(在图和图例中)?

您可以使用scale_shape_discrete设置solid = FALSE:

ggplot(df, aes(x = x, y = y)) + 
  geom_line(aes(colour = factor(group, labels = c("a", "b", "c")))) +
  scale_shape_discrete(solid = F) +
  geom_point(aes(colour = factor(group, labels = c("a", "b", "c")),
                 shape = factor(group, labels = c("a", "b", "c")))) +              
theme(legend.title = element_blank())

ggplot2 使用的默认形状只有一种颜色: 颜色和填充,你必须使用从 21 到 25 的点形状。然后设置 fill = "white" 有效:

library(ggplot2)

df <- data.frame(
  y = 1:10, x = 1:10,
  group = factor(rep(1:3, c(3, 3, 4)), labels = letters[1:3])
)

ggplot(df, aes(x = x, y = y, colour = group)) +
  geom_line() +
  geom_point(aes(shape = group), fill = "white", size = 3) +
  theme(legend.title = element_blank()) +
  scale_shape_manual(values = 20 + seq_along(unique(df$group)))

如果您不使用标准形状,想出一个解决方案 21:25。诀窍是调用 geom_point 两次,一次使用形状 21 来清理重叠线,另一次来覆盖所需的形状。

library(ggplot2)
library(RColorBrewer)
Paired = brewer.pal(n=10, name="Paired")
unicodeShapes = -10122:-10131

df = data.frame(y = 1:10, x = 1:10, labels = LETTERS[1:10])

ggplot(data=df,aes(x=x, y=y)) +
  geom_line(color="gray50") + 
  geom_point(aes(x=x, y=y), color="white", shape=21, fill="white", size=5.0,show.legend=FALSE) + 
  geom_point(aes(color=labels, shape=labels), size=6.5) + 
  scale_shape_manual(name="Labels",values=unicodeShapes) +
  scale_color_manual(name="Labels",values=Paired) +
  theme_classic()+
  theme(axis.line.x=element_line(color="gray20", size=1.0),
        axis.line.y=element_line(color="gray20", size=0.5),
        panel.grid.major.x=element_blank(),
        panel.grid.minor=element_blank(), 
        panel.border=element_rect(colour="gray50",fill=NA,size=1.0),
        panel.background = element_rect(colour = "gray50", size=1.0),
        legend.position="bottom",
        text=element_text(size=18))

Shapes on top of line