Reputation: 105
I want to visualize the elements of my vectors in a graph. I want to generate a graph with a certain x- and y-axis and then put the values of my vectors as points into the graph. I also want different colors for the values of the different vectors. How do I do that?
For example: I have 10 elements in vector A and want to put those elements into the graph. The first Element of vector A has the y-value A[1] and the x-value 1. The second Element of vector A has the y-value A[2] and the x-value 2. Same with vector B.
vec1 = 1:10
vec2 = 1:10
for(idx in 1:10){
vec1[idx] = runif(1, min=0, max=100)
vec2[idx] = runif(1, min=0, max=100)
}
plot(vec1 and vec2) // How do I do this?
dput output for vec1: c(81.9624423747882, 45.583715592511, 56.2400584807619, 8.25600677635521, 82.0227505406365, 45.6240070518106, 68.7916911672801, 94.491201499477, 22.0095717580989, 4.29550902917981)
dput output for vec2: c(29.5684755546972, 68.0154771078378, 52.2058120695874, 2.48502977192402, 91.9532125117257, 24.7736480785534, 66.5003522532061, 79.014728218317, 47.9641782585531, 20.5593338003382)
Upvotes: 2
Views: 1801
Reputation: 506
I think the easiest is to create a data frame, which is usually what most functions expect in R:
library(tidyverse)
vec1 = 1:10
vec2 = 1:10
for(idx in 1:10){
vec1[idx] = runif(1, min=0, max=100)
vec2[idx] = runif(1, min=0, max=100)
}
df <- data.frame(order = 1:10, vec1, vec2) %>%
pivot_longer(!order, names_to = "color", values_to = "value")
plot(df$order, df$value, col = c("red","blue")[df$color %>% as.factor()])
Upvotes: 1
Reputation: 263362
Starting with
vec1 = 1:10
vec2 = 1:10
for(idx in 1:10){
vec1[idx] = runif(1, min=0, max=100)
vec2[idx] = runif(1, min=0, max=100)
}
plot(vec1 and vec2) // How do I do this?
Try this:
plot( 1:20, c(vec1,vec2) , col=rep(1:2,10) # just points
lines( 1:20, c(vec1,vec2) ) # add lines
# if you wanted the same x's for both sequences the first argument could be
# rep(1:10, 2) instead of 1:20
Note: Your set up code could have been just two lines (no loop):
vec1 = runif(10, min=0, max=100)
vec2 = runif(10, min=0, max=100)
Upvotes: 2
Reputation: 263362
I'm wondering or guessing whether you are aiming for the facility provided by teh base-plotting function arrows? This is the example in the ?arrows page:
x <- stats::runif(12); y <- stats::rnorm(12)
i <- order(x, y); x <- x[i]; y <- y[i]
plot(x,y, main = "arrows(.)" )
## draw arrows from point to point :
s <- seq(length(x)-1) # one shorter than data
arrows(x[s], y[s], x[s+1], y[s+1], col = 1:3)
If you wanted instead to plot with each vector (represented by "arrows") starting from the origin it would be:
x <- stats::runif(12); y <- stats::rnorm(12)
# ordering not needed this time
plot(x,y, main = "arrows(.)", xlim=c(0, max(x)) # to let origin be seen)
## draw arrows from origin to point :
s <- length(x) # one shorter than data
arrows(rep(0,s), rep(0,s), x, y, col = 1:3)
Upvotes: 0