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

R语言ggplot2中geom_col(width=1)适配及样式调整求助

解决ggplot2中geom_col的区间适配与图案填充问题

问题分析

原代码用factor(Y)将连续y值转为离散类别,导致灰色区域仅对应±0.05两个孤立柱子,无法精准覆盖-0.1到0.1区间;同时ggplot2原生不支持填充图案,需借助扩展包实现绿色区域的斜线样式。

解决方案

1. 重构数据结构

将每个数值区间(如-0.5-0.3、-0.3-0.1等)作为单独条目,明确区间上下限、填充色及图案参数。

2. 用ggpattern添加图案

借助ggpattern包的geom_col_pattern实现绿色区域的斜线填充,可自定义角度和密度。

完整代码

library(dplyr)
library(ggplot2)
library(ggpattern)

# 重构数据:定义每个区间的上下限、填充色和图案参数
df <- tibble(
  x = 9,
  y_min = c(-0.5, -0.3, -0.1, 0.1, 0.3),
  y_max = c(-0.3, -0.1, 0.1, 0.3, 0.5),
  fill_color = case_when(
    y_min == -0.1 & y_max == 0.1 ~ "grey",
    TRUE ~ "#6BD7AF"
  ),
  pattern = ifelse(fill_color == "#6BD7AF", "hatch", "none"),
  pattern_angle = 45,    # 斜线角度
  pattern_density = 0.2, # 斜线密度(数值越大线条越密)
  pattern_color = "#333333" # 斜线颜色
) %>%
  mutate(
    height = y_max - y_min, # 柱子高度
    y_mid = (y_min + y_max)/2 # 柱子中心位置
  )

# 绘制图表
ggplot(df, aes(x = x, y = height, fill = fill_color)) +
  geom_col_pattern(
    width = 1,
    aes(
      pattern = pattern,
      pattern_angle = pattern_angle,
      pattern_density = pattern_density,
      pattern_color = pattern_color
    )
  ) +
  # 自定义填充色与图例
  scale_fill_manual(
    name = "",
    values = c("#6BD7AF" = "#6BD7AF", "grey" = "grey"),
    labels = c("Incorrect", "Correct")
  ) +
  scale_pattern_manual(
    name = "",
    values = c("hatch" = "hatch", "none" = "none"),
    labels = c("Incorrect", "Correct")
  ) +
  # 坐标轴设置
  scale_y_continuous(
    breaks = seq(-0.5, 0.5, by = 0.2),
    labels = seq(-0.5, 0.5, by = 0.2)
  ) +
  scale_x_continuous(
    breaks = seq(1, 9, by = 1),
    limits = c(1, 9)
  ) +
  theme_classic() +
  labs(y = "y", x = "x") +
  coord_cartesian(expand = FALSE)

关键调整说明

  • 将离散Y值改为连续区间,确保灰色区域精准覆盖-0.1到0.1范围;
  • 用ggpattern::geom_col_pattern替代原生geom_col,通过pattern_angle和pattern_density控制斜线的角度和密度;
  • 统一图例设置,避免填充色和图案出现重复图例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 18:00:51