如何制作包含交替颜色段的 ggplot2 线图,在弯曲处没有小间隙?

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

我的目标是使用 ggplot2 在 R 中制作专业外观的折线图。
我的折线图根据 data$color 中的值具有交替颜色。然而,这条线看起来像块状矩形线段。线条整体呈块状、碎片化。如何修改绘图以保留颜色段并具有平滑的连续连接点?

下面是一个简化示例的代码及其生成的绘图。

data <- data.frame(
  x = 1:15,
  y = round(c(0.0146,0.0025,0.0647,0.0311,-0.0177,-0.0487,-0.022,0.0892,0.0442,0.0159,0.0517,0.031,-0.0416,0.048,0.0347), digits = 2)
)

data$color <- "green"
data$color[8:12] <- "blue"

my_plot <- ggplot(data, aes(x = x)) +
  geom_line(aes(y = y, color = color, group = 1), size = 1) +
  scale_colour_identity()

ggsave("test_green_blue.png", plot = my_plot, bg = "white", width = 10, height = 4)

Line plot with alternating green and blue segments. Blocky junctions and appears fragmented

下面是特写: Zoomed in blocky junctions

下面是我正在寻找的平滑连续外观的示例。

data <- data.frame(
  x = 1:15,
  y = round(c(0.0146,0.0025,0.0647,0.0311,-0.0177,-0.0487,-0.022,0.0892,0.0442,0.0159,0.0517,0.031,-0.0416,0.048,0.0347), digits = 2)
)

my_plot <- ggplot(data, aes(x = x)) +
  geom_line(aes(y = y), size = 1)

ggsave("test_default.png", plot = my_plot, bg = "white", width = 10, height = 4)

Example of a smooth continuous line plot

r ggplot2 plot graph colors
1个回答
0
投票

使用 geom_line() 的 lineend 参数

lineend = "round"
© www.soinside.com 2019 - 2024. All rights reserved.