Lanorius94
Lanorius94

Reputation: 27

How to use ggplot2 to create a graph with multiple y values per x and x values from a vector

first let's say I have a vector:

a <- c(1, 4, 5, 10) 

The above are the values for the x-axis

and a matrix

b <- matrix(c(1,2,3,4,5,6,7,8,9,10,11,12),nrow=3,ncol=4)
b
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12

As you see the x value for the first column is 1, for the second it is 4 aso, and each x value has three y values.

How do I use geom_plot() + geom_point() to plot all of these points in a single graph?

Upvotes: 0

Views: 1752

Answers (2)

Roman
Roman

Reputation: 17648

You can try a tidyverse. The trick is the transformation of the data from wide to long using gather.

library(tidyverse)
data.frame(a, t(b))  %>% 
  gather(k, v,-a) %>% 
  ggplot(aes(a, v, group = k)) + 
   geom_point() +
   geom_line()

enter image description here

Instead of group you can als do color = k to add colors.

In base R you can try

plot(a, xlim=range(a), ylim = range(b), type = "n")
sapply(1:nrow(b), function(x){ lines(a, b[x,], col =x) ; points(a, b[x,], col =x)})

enter image description here

Upvotes: 2

kath
kath

Reputation: 7724

First of all you needto store your data in a dataframe for ggplot. As the columns correspond to the different a - values I transpose b and then the rows correspond to the a values:

my_df <- as.data.frame(t(b))
my_df$a <- a
my_df
#   V1 V2 V3  a
# 1  1  2  3  1
# 2  4  5  6  4
# 3  7  8  9  5
# 4 10 11 12 10

Then to have a color for the different columns the easiest way ist to transform your data from wide format to long format with gather:

library(tidyr)

my_df_long <- gather(my_df, group, y, -a)

Then you can plot your data:

library(ggplot2)

ggplot(my_df_long, aes(a, y, color = group)) +
  geom_point()

enter image description here

Upvotes: 1

Related Questions