0

How can I create a plot with different facet based on each column but still the same value of x base on the row names.

Let's say I have a summary from regsubsets() but since it returns a list I have to make it as a data frame first (is there anyway I can use ggplot2 with list?).

set.seed(1)
X = rnorm(100)
e = rnorm(100)
Y = 8 + 7*X + 2.5*X^2 - 9*X^3 + e
regfit.full = regsubsets(Y~poly(X,10,raw=T), data=data.all, nvmax=10)
(reg.summary = summary(regfit.full))

df = data.frame(reg.summary$cp, reg.summary$bic, reg.summary$adjr2)
> names(df)
[1] "reg.summary.cp"    "reg.summary.bic"   "reg.summary.adjr2"

> dim(df)
[1] 10  3

Now the question is how can I make a facet for each features (i.e. reg.summary.cp, reg.summary.bic, reg.summary.adjr2) that will be the value on the y-axis and the value for the x-axis will be the row number.

1 Answer 1

2

Could be done by adding rownumbers and melting the dataframe using reshape2:

library(reshape2)
library(ggplot2)

data.all = data.frame()

set.seed(1)

X = rnorm(100)
e = rnorm(100)
Y = 8 + 7 * X + 2.5 * X ^ 2 - 9 * X ^ 3 + e

regfit.full = regsubsets(Y ~ poly(X, 10, raw = T), data = data.all, nvmax = 10)
(reg.summary = summary(regfit.full))

df = data.frame(reg.summary$cp, reg.summary$bic, reg.summary$adjr2)
df$rownum <- 1:NROW(df)

molten_df <- melt(df, id.vars = "rownum")

ggplot(data = molten_df, aes(x = rownum, y = value)) +
  geom_point() +
  facet_wrap( ~ variable)

enter image description here

EDIT: maybe make the y-axes independet from one another by adding scales = "free_y" So:

ggplot(data = molten_df, aes(x = rownum, y = value)) +
  geom_point() +
  facet_wrap( ~ variable, scales = "free_y")

enter image description here

EDIT2: a way to make the plot without melting df:

grid.arrange(
  ncol = 3,
  ggplot(data = df) +
    geom_point(aes(x = rownum, y = reg.summary.cp)),
  ggplot(data = df) +
    geom_point(aes(x = rownum, y = reg.summary.bic)),
  ggplot(data = df) +
    geom_point(aes(x = rownum, y = reg.summary.adjr2))
)
Sign up to request clarification or add additional context in comments.

1 Comment

do I really need to melt the df? and is it possible to make the scale of y for each facet base on each range in column not by overall data frame?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.