1

I have a matrix in R that I can plot using matplot however it is hard to customize the plot. I would like to plot using the R package ggplot however it will not work using a matrix. I am not sure what transformations are required of the matrix to allow the data to work with ggplot.

Thanks for any help.

3
  • You could coerce to a dataframe with as.data.frame, then add column names with the colnames argument. Commented Jun 6, 2017 at 2:03
  • Have you tried as.data.frame() function to transform? Commented Jun 6, 2017 at 2:17
  • 2
    a reproducible example will help a lot. You can try (1) as.data.frame.table() (2) reshape2::melt() Commented Jun 6, 2017 at 2:23

2 Answers 2

1

you need to convert the matrix to a data frame

    mat  = cbind(index = seq(1:10), price=7+rnorm(10))
    df = as.data.frame(mat)
    library(ggplot2)
    ggplot(df) + geom_line(aes(x = index, y = price))
Sign up to request clarification or add additional context in comments.

Comments

0

You can use reshape2::melt as mentioned in the comment. Here is a reproducible example.

library(ggplot2)
# generating a random matrix
numbers <- sample(c(1:100), 100, replace = T)
data <- matrix( numbers, ncol=10)
rownames(data) <- paste0("row-", seq(1,10))
colnames(data) <- paste0("col-", seq(1,10))
data # a matix
#  converting to a ggplot dataframe
df <- reshape2::melt(data, c("row", "col"), value.name = "values")
head(df)
# plotting
ggplot(df, aes(x = col, y = values)) + geom_boxplot() #group by columns
ggplot(df, aes(x = row, y = values)) + geom_boxplot() #group by rows

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.