ggplot2:线条+点用白色填充图和图例?

时间:2019-01-07 12:02:50

标签: r ggplot2 plot fill points

我想用ggplot2包创建一个将线和点结合在一起的图。这些点应根据组指示符具有颜色和形状。应该创建一个图例,根据图例显示颜色和形状。

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

谷歌搜索建议使用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())

enter image description here

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

3 个答案:

答案 0 :(得分:2)

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)))

答案 1 :(得分:1)

您可以使用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())

enter image description here

答案 2 :(得分:1)

如果不使用标准形状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