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

如何用ggplot2制作足球两队对比双条形图并解决绘图问题

解决ggplot2复刻足球双条形对比图的问题

以下是针对你提出的4个问题的解决方案及完整代码:

问题解决说明

  • 刻度范围过大:用分面将每个指标单独展示,且每个分面使用独立刻度,避免数值差异大导致的细节丢失。
  • type标签居中:将指标标签作为分面的strip放在左侧,设置居中对齐,替代原y轴标签。
  • 数值标签位置错误:根据数值正负动态调整标签的水平对齐方式,确保标签始终在条形顶端。
  • 添加队徽:使用ggimage包的geom_image将队徽定位到图表的左右上角。

完整代码

# 加载所需包
library(ggplot2)
library(ggimage)
library(dplyr)

# 提取两队唯一队徽链接
eng_logo <- df %>% filter(name == "England") %>% pull(logo) %>% unique()
iran_logo <- df %>% filter(name == "Iran") %>% pull(logo) %>% unique()

# 绘制图表
ggplot(df, aes(x = type, y = value, fill = name)) +
  # 绘制条形图,隐藏图例
  geom_col(show.legend = FALSE) +
  # 添加数值标签,根据正负调整位置
  geom_text(
    aes(label = abs(value), hjust = ifelse(value > 0, 1.1, -0.1)),
    size = 3, color = "black"
  ) +
  # 分面:每个指标单独面板,自由y轴,标签在左侧
  facet_wrap(~type, scales = "free_y", ncol = 1, strip.position = "left") +
  # 翻转坐标轴
  coord_flip() +
  # 使用极简主题
  theme_minimal() +
  # 调整主题样式
  theme(
    # 设置左侧指标标签居中、加粗
    strip.text.y = element_text(hjust = 0.5, size = 10, face = "bold"),
    # 隐藏原y轴的刻度和标签
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank(),
    # 隐藏轴标题
    axis.title = element_blank(),
    # 减小面板间距,让布局更紧凑
    panel.spacing = unit(0.1, "lines")
  ) +
  # 添加英格兰队徽到右上角
  geom_image(
    aes(x = Inf, y = -Inf, image = eng_logo),
    hjust = 1.1, vjust = -0.1, size = 0.08
  ) +
  # 添加伊朗队徽到左上角
  geom_image(
    aes(x = -Inf, y = -Inf, image = iran_logo),
    hjust = -0.1, vjust = -0.1, size = 0.08
  )

代码解释

  1. 分面设置:facet_wrap(~type, scales = "free_y", ncol = 1, strip.position = "left") 让每个指标拥有独立的y轴刻度,同时将指标标签移到左侧,替代原y轴。
  2. 标签对齐:hjust = ifelse(value > 0, 1.1, -0.1) 确保英格兰(正值)的标签在条形右侧,伊朗(负值)的标签在条形左侧,都处于条形顶端位置。
  3. 队徽添加:通过x = Inf和x = -Inf定位到图表的左右边缘,hjust和vjust微调位置,size控制图标大小,避免遮挡图表内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 16:30:45