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

R语言使用ggplot2复现目标图形的异常问题修复咨询

修复方案

三个问题的对应调整方法如下:

  • 针对虚线形态异常、X轴尺寸不符合预期的问题:原代码错误将数值类型的x、y轴配置为离散轴,导致坐标比例失真,虚线也因离散化显示异常。将scale_y_discrete、scale_x_discrete替换为连续轴配置,x轴的自定义标签通过连续轴的breaks和labels参数实现即可。
  • 针对多边形中间多余白线的问题:原代码单独绘制了两个相邻的多边形,且都设置了白色边框,相邻的公共边就会显示为白线。直接去掉geom_polygon的color参数即可消除白线。
  • 额外修正:原代码缺少ggplot2包加载语句,且geom_polygon中alpha参数取值超出0-1的有效范围,一并修正。

调整后完整代码

library(ggplot2)
library(dplyr)
library(scales)
d <- data.frame(x=c(4.5,9,5.5), y=c(3.5,2.5,8))
f <- data.frame(x=c(9,10,5.5), y=c(2.5,2.5,8))
df <- data.frame(x1 = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) , y1 = c(1, 4, 2.5, 4.5, 5.5, 8.5, 2.5, 1, 1.5, 2.5), x2 = 1:10, y2 = 1:10, x3 = c(2.1875, 5.8125, 6.25, 8.125, 9.3125), y3 = c(7.5, 6.375, 3, 3.875, 2.1875), x4 = c(1.3125, 1.5, 1.6875, 3.6875, 7.25), y4 = c(7.1875, 9.9375, 9.0625, 9.375, 3.8125))
grafico_4 <- ggplot(df) +
  ggtitle("Grafico variado") +
  theme(plot.title = element_text(size = 10)) +
  theme(panel.background = element_rect(fill='white', colour='white')) +
  theme( axis.line = element_line(colour = "black", size = 0.5)) +
  scale_y_continuous(breaks = 1:10, limits = c(1,10)) +
  scale_x_continuous(breaks = 1:10, labels = c("uno", "", "tres", "", "cinco", "", "siete", "", "nueve", ""), limits = c(1,10)) +
  geom_polygon(data = d, mapping=aes(x = x, y = y), fill = "#AED9E6") +
  geom_polygon(data = f, mapping=aes(x = x, y = y), fill = "#AED9E6") +
  geom_hline(yintercept = 5, linetype = "dotted") +
  xlab("") +
  ylab("") +
  geom_line(aes(x = x1, y = y1), size = 1, alpha = 0.9, linetype = 2) + 
  geom_point(aes(x = x2, y = y2), shape = 1) +
  geom_point(aes(x = x3, y = y3), shape = 1, color = "red") +
  geom_point(aes(x = x4, y = y4), shape = 3, color = "green", size = 0.8) +
  annotate(geom = "text", x = 1.7, y = 7.5, label = "cinco", color = "purple", size = 3) +
  annotate(geom = "text", x = 2, y = 6, label = "dos", color = "yellow", size = 3) +
  annotate(geom = "text", x = 6.625, y = 9.125, label = "cuatro", color = "blue", size = 3) +
  annotate(geom = "text", x = 7.875, y = 2, label = "tres", color = "green", size = 3)

# 输出图形
print(grafico_4)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:15:06