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

如何用ggplot连接特定数据点?现有代码无法实现需求

Solution

First, we need to restructure your data to create proper grouping and ordering variables, then filter the data used for lines to only include the points you want connected.

Step 1: Prepare the Data

Split V1 into two components: the main group (1, 2, 3) and position (a-f). We'll also enforce correct ordering for the x-axis to ensure points connect in the right sequence.

library(ggplot2)
library(dplyr)
library(stringr)

# Process the raw data
df_processed <- df %>%
  mutate(
    # Extract the numeric group from V1
    main_group = str_extract(V1, "\\d+"),
    # Extract the position letter from V1
    position = str_extract(V1, "[a-z]"),
    # Convert position to a factor to fix x-axis order (a → f)
    position = factor(position, levels = c("a", "b", "c", "d", "e", "f"))
  )

Step 2: Create the Plot

Use geom_point to display all data points, and geom_line with a filtered subset of data (only positions c-f) to draw the desired lines.

ggplot(df_processed, aes(x = position, y = V2)) +
  # Show all points, colored by main group
  geom_point(aes(color = main_group), size = 3) +
  # Draw lines only between c-f points, grouped by main group
  geom_line(
    data = df_processed %>% filter(position %in% c("c", "d", "e", "f")),
    aes(group = main_group, color = main_group),
    linewidth = 1
  ) +
  labs(
    x = "Position",
    y = "V2 Value",
    color = "Group"
  ) +
  theme_minimal()

Why This Fixes the Issue

  • Proper Grouping: Using main_group (1, 2, 3) instead of V1 tells ggplot to connect all points in the same core group.
  • Targeted Filtering: The geom_line only uses rows where position is c-f, so it won't connect a/d or b/e points.
  • Controlled Ordering: Converting position to a factor ensures the x-axis follows a → f order, so lines connect in the correct sequence.

Notes

  • If you don't have stringr installed, run install.packages("stringr") first.
  • Adjust size and linewidth values to match your preferred visual style.

内容的提问来源于stack exchange,提问作者B.Nin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:15:36