Reputation: 27
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
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()
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)})
Upvotes: 2
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()
Upvotes: 1