小编Eli*_*ias的帖子

ggplot:为什么我必须将数据转换为长格式?

使用 ggplot 绘图时,我经常需要将数据转换为长格式,例如下面的代码。我有两个问题:

  1. 有没有办法将列(因此每个变量)用作“组”?那么每列都被绘制并具有不同的颜色吗?因此,无需将数据转换为长格式。(无需将每个变量放入 a 中geom_line()
  2. 为什么必须将数据转换为长格式?其背后的原因是什么?当数据具有宽格式时,它比绘图更好吗?

示例代码:

library(tidyverse) 
# Data in wide format
  df_wide <- data.frame(
   Horizons = seq(1,10,1),
   Country1 = c(2.5, 2.3, 2.2, 2.2, 2.1, 2.0, 1.7, 1.8, 1.7, 1.6),
   Country2 = c(3.5, 3.3, 3.2, 3.2, 3.1, 3.0, 3.7, 3.8, 3.7, 3.6),
   Country3 = c(1.5, 1.3, 1.2, 1.2, 1.1, 1.0, 0.7, 0.8, 0.7, 0.6)
   )

# Convert to long format
  df_long <- df_wide %>%
   gather(key = "variable", value = "value", -Horizons)
    
# Plot the lines
  plotstov …
Run Code Online (Sandbox Code Playgroud)

r ggplot2 dataframe

5
推荐指数
1
解决办法
4546
查看次数

标签 统计

dataframe ×1

ggplot2 ×1

r ×1