繁体   English   中英

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

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

我想用 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())

在此处输入图片说明

问题:我怎么能用白色填充这个图的点(在图和图例中)?

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

线条顶部的形状

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM