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

如何转换R数据框行列并绘制美国交通工具的Spaghetti Plot

解决方法

首先我们先构造符合你描述的示例数据框:

# 构造示例数据框
df <- data.frame(
  Year = c(2010, 2011, 2012),
  Country = rep("美国", 3),
  Car = c(1200, 1350, 1500),
  Bike = c(800, 750, 700),
  Truck = c(500, 600, 650)
)

接下来用tidyr包的pivot_longer()函数将宽格式转换为你需要的长格式,这个操作不会打乱Year列,同时把交通工具类型转为单独的列:

library(tidyr)

# 转换为长格式数据框
long_df <- df %>%
  pivot_longer(
    cols = c(Car, Bike, Truck),  # 指定要转换的交通工具列
    names_to = "Type",           # 新生成的类型列名称
    values_to = "Value"          # 对应数值的列名称
  )

转换后的长格式数据框结构如下(可通过head(long_df)查看):

YearCountryTypeValue
2010美国Car1200
2010美国Bike800
2010美国Truck500
2011美国Car1350
2011美国Bike750
2011美国Truck600

最后用ggplot2绘制Spaghetti Plot,以年份为横轴、数值为纵轴,按交通工具类型区分线条和图例:

library(ggplot2)

ggplot(long_df, aes(x = Year, y = Value, color = Type, group = Type)) +
  geom_line(linewidth = 1) +  # 绘制线条
  geom_point(size = 3) +      # 加入数据点增强可读性
  labs(
    title = "美国2010-2012年交通工具数量变化",
    x = "年份",
    y = "数量",
    color = "交通工具类型"
  ) +
  theme_minimal()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:15:44