在 R 中,如何为点提供不同的形状和填充,显示 ggplot 中填充的图例?

问题描述 投票:0回答:0

例如,我有如下数据,

population=rep(c("High", "Low"), time=5)
year=rep(c("2020_H","2020_L","2020_O","2021_L","2021_O"), each=2)
x=c(10,20,30,40,50,60,70,80,90,100)
y=c(15,25,35,45,55,75,100,120,125,145)

dataA=data.frame(population,year,x,y)

   population year    x   y
1        High 2020_H  10  15
2         Low 2020_H  20  25
3        High 2020_L  30  35
4         Low 2020_L  40  45
5        High 2020_O  50  55
6         Low 2020_O  60  75
7        High 2021_L  70 100
8         Low 2021_L  80 120
9        High 2021_O  90 125
10        Low 2021_O 100 145

ggplot(data=dataA, aes(x=x, y=y))+
  stat_smooth(method='lm', linetype=1, se=FALSE, formula=y~x, linewidth=0.5, 
              color="dark red") +
  geom_point(aes(fill=year, shape=population), color="black", size=4) +
  scale_fill_manual(values= c("Dark red","Dark blue", "Orange", "purple", "dark green"))+
  scale_shape_manual(values=c(21,24))+
  scale_x_continuous(breaks=seq(0,100,20),limits=c(0,100))+
  scale_y_continuous(breaks=seq(0,150,50),limits=c(0,150))+
  guides(shape="none") +
  theme_classic(base_size=16, base_family="serif")+
  theme(legend.position=c(0.8, 0.2),
        legend.title=element_blank(),
        legend.key=element_rect(color=alpha("grey",.05), fill=alpha("grey",.05)),
        legend.background= element_rect(fill=alpha("grey",.05)),
        axis.line=element_line(linewidth=0.5, colour="black"))+
windows(width=5.5, height=5)

我生成了一张图表。我为人口提供了不同的形状,为年份提供了不同的颜色。然后,我使用

guides(shape="none")
隐藏形状的图例。但是,填充图例没有提供正确的颜色索引。我想在一年的传说中展示不同的颜色。

你能告诉我怎么做吗?

总是非常感谢!

r ggplot2 legend shapes fill
© www.soinside.com 2019 - 2024. All rights reserved.