leeper / margins

An R Port of Stata's 'margins' Command
https://cloud.r-project.org/package=margins
Other
260 stars 39 forks source link

Label mismatch between margins() and plot(margins())? #185

Open PrisonRodeo opened 2 years ago

PrisonRodeo commented 2 years ago

Hi -

I'm seeing mismatched labels between margins(foo) and plot(margins(foo)), in this case for a logit (no interactions). I hope I'm not doing something wrong. Reproduceable minimal example below. The issue seems to arise when the variables in the fitted model appear in a different order than they do in the data frame.

Thanks,

-- CZ (zorn@psu.edu, @prisonrodeo)

==================================== Please specify whether your issue is about:

Code!

library("margins")
set.seed(7222009)
df<-data.frame(X1=rbinom(400,1,0.5),
               X2=runif(400,0,1),
               X3=rbinom(400,1,0.2))
df$Y<-rbinom(400,1,plogis(1*df$X1+3*df$X2-3*df$X3))
hat<-glm(Y~X1+X2+X3,df,family="binomial")
margins(hat)
plot(margins(hat))  # <- works OK
hat2<-glm(Y~X3+X2+X1,df,family="binomial")
margins(hat2)
plot(margins(hat2)) # <- mismatches labels to AMEs

## session info for your system
sessionInfo()
jsavinc commented 1 year ago

I've encountered the same, it appears that the labels are in the order of the fitted mode, but the plots are in alphabetical order of variable names.