You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为ggplot2的geom_point设置不同填充色与边框颜色?

解决ggplot2 geom_point边框颜色不生效问题

你的代码中scale_color_manual设置的边框色不生效,核心原因是**geom_point里设置了stroke = 0**——stroke参数控制点边框的粗细,设为0会完全隐藏边框,导致边框颜色无法显示。

修正方案:

  1. 保留shape = 21(该形状支持独立设置填充色fill和边框色color)
  2. 将stroke改为大于0的数值(比如stroke = 1,可根据需求调整粗细)

修正后的完整代码:

#install.packages("Lahman")
library(Lahman)
library(ggthemes)
library(dplyr) # 需加载dplyr以支持filter和管道符

team_wins <- filter(Teams, yearID > 1990 & yearID != 1994 & yearID !=2020,
                    franchID %in% c('NYM','WSN','ATL','PHI','FLA'))

graph1 = team_wins %>%
  ggplot(aes(x=W, y=attendance)) +
  geom_point(alpha = 0.7, stroke = 1, shape = 21, size = 4, 
             aes(color = factor(franchID),
                 fill = factor(franchID))) +
  theme_fivethirtyeight() +
  labs(title = "Wins by NL East Teams over Time",
       subtitle = "From 1991 Onward", # 与数据筛选条件统一,可按需修改
       x = "# of Wins",
       y = "Attendance",
       caption = "Source: Lahman Data") +
  theme(axis.title = element_text(),
        text = element_text(family = "Trebuchet MS"),
        legend.text = element_text(size = 10)) +
  theme(legend.title = element_text(hjust = 0.5)) +
  scale_x_continuous(breaks = c(seq(55,110,5))) +
  scale_y_continuous(breaks = c(seq(0,5000000,1000000))) +
  scale_fill_manual(values = c("NYM" = "#002D72", 
                                "ATL" = "#CE1141",
                                "FLA" = "#00A3E0", 
                                "PHI" = "#E81828", 
                                "WSN" = "#14225A")) +
  scale_color_manual(values = c("NYM" = "#FF5910", 
                               "ATL" = "#13274F",
                               "FLA" = "#EF3340", 
                               "PHI" = "#FFFFFF", 
                               "WSN" = "#AB0003"))

graph1

另外注意:你的副标题写的是"From 1980 Onward",但数据筛选条件是yearID > 1990,两者不一致,可根据实际需求调整统一。

内容的提问来源于stack exchange,提问作者Violin125

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 23:47:38