statslover
statslover

Reputation: 1

How can you change plots into ggplot format?

I have a problem changing plot in ggplot format. The data I used in plot is match.obj. Info about match.obj

when plotting the object with this code:

plot(match.obj,type = "hist") 

I received the following picture.

enter image description here

As I did using fortify to change data type to make it compatible for ggplot:

my_data <- fortify(POD_dataset) # data for ggplot use

it gave me an error.

Fehler: data must be a data frame, or other object coercible by fortify(), not an S3 object with class matchit.

How can you change the format so that iit is compatible for ggplot?

So I will make my question more clear with the help of my code. My question is at the end.

m.out1<-matchit(formula = ps.formula,data = POD_dataset,
                   distance = POD_dataset$PS,
                   method = "nearest" , replace = FALSE,
                   caliper = .1*sd(logitPS),ratio = 1)
POD_dataset$PS <- m.out1$distance
summary(m.out1$distance)
m.out1
summary(m.out1)


library("MatchIt")
matches <- as.data.frame(m.out1$match.matrix)
colnames(matches) <- c("matched_unit")
matches$matched_unit <- as.numeric(
  as.character(matches$matched_unit))
matches$treated_unit <-as.numeric(rownames(matches))
matches.only <- matches[!is.na(matches$matched_unit),]
head(matches.only)
POD_dataset[POD_dataset$id  %in% as.numeric(matches.only[2,]),]

I used this (below) code to create the normal plot. And I obtained the normal histogram that is shown below.

plot(m.out1,type = "hist")

But I want m.out1 plot in ggplot, My question is : How can I get the object m.out1 in ggplot. Please, can anyone help me.

Upvotes: 0

Views: 230

Answers (1)

Daniel D
Daniel D

Reputation: 119

Your problem is that you try to plot a matchit object. This object is basically a list of different items. So you need to pick the item that you want to plot.

I used an example from the documentation to illustrate how you can get the results into a data frame.

library(MatchIt)
data("lalonde")

# Default: 1:1 NN PS matching w/o replacement
m.out1 <- matchit(treat ~ age + educ + race + nodegree +
                    married + re74 + re75, data = lalonde)
m.out1
summary(m.out1)

# Select the table you want to use for plotting and save it as a separate object.

df <- m.out1$X

I hope this helps 😉. It is certainly easier if you can provide example code we can use to solve your problem.

Upvotes: 1

Related Questions