anuja
anuja

Reputation: 170

plot graph using values based on multiple columns in R

I would like to plot a graph between v1 and v4 for the subset of equal values of (v2,v3,v5) and that too in same graph. My dataset is as follows

v1  v2 v3 v4        v5
 3  10 20  1 0.5000000
 1  10 20  2 0.5000000
 2  10 30  1 0.3333333
 1  10 30  2 0.3333333
 1  10 40  1 0.2500000
 1  10 45  1 0.2222222
 1  10 45  1 0.2222222

group_by is giving same matrix as above.

Ex: plot one graph of these values

v1  v2 v3 v4        v5
 3  10 20  1 0.5000000
 1  10 20  2 0.5000000

Upvotes: 0

Views: 222

Answers (1)

Anders Ellern Bilgrau
Anders Ellern Bilgrau

Reputation: 10223

Not pretty code, but the below does what you want in base R.

df <- read.table(header = TRUE, text = 
"v1  v2 v3 v4        v5
3  10 20  1 0.5000000
1  10 20  2 0.5000000
2  10 30  1 0.3333333
1  10 30  2 0.3333333
1  10 40  1 0.2500000
1  10 45  1 0.2222222
1  10 45  1 0.2222222")

cols <- c("v2", "v3", "v5")
df.u <- unique(df[,cols]) # Get unique rows

# Initialise plot
plot(1, type = "n", xlim = range(df[,"v1"]), ylim = range(df[,"v4"]))

for (i in seq_len(nrow(df.u))) {
  # Subset to unique row
  df.sub <- df[df$v2==df.u$v2[i] & df$v3==df.u$v3[i] & df$v5==df.u$v5[i], ]
  # Plot
  lines(df.sub$v1, df.sub$v4, col = i, type = "b", pch = i, lty = i)
}

Upvotes: 1

Related Questions