首页 > 解决方案 > 从边距图中删除分类 x 轴名称

问题描述

我想为从 margins 包返回的平均边际效应输出一个图。变量位于 x 轴上,但它们的顺序不正确,并且未显示所有变量名称。我想以正确的顺序显示所有变量名称并旋转 90 度。这是我的代码:

margins_logit <- margins(LOGIT, variables=c("AGE", "AGE_SQRD", "LOGINCOME", "LOGINCOME_SQRD", "LOGSPEND", "LOGSPEND_SQRD"))

categories <- c(
                "AGE",
                "AGE_SQRD",
                "LOGINCOME",
                "LOGINCOME_SQRD",
                "LOGSPEND",
                "LOGSPEND_SQRD"
)

plot(margins_var, main="", xlab ="", xaxt='n', ann=TRUE)
axis(1, at=1:6, labels=categories, las = 2, cex.axis = 0.8)

我遵循了这个:删除绘图轴值,但它似乎对我不起作用。

非常感谢!

本都

垂直 x 类别值是正确的,但水平位置错误,并且所有类别均未显示。我想完全删除这些并用轴替换它们。

标签: rplot

解决方案


'xaxt' 适用于大多数绘图,但对于您有一个边距对象并且您margins:::plot.margins在运行时调用 this plot(margins_var..)。在 margins:::plot.margins 内部,他们实际上使用轴命令放置了标签,因此您会看到两次标签。

我没有您的数据,所以我使用 mtcars 示例向您展示 2 个解决方法:

library(margins)
fit <- lm(mpg ~ cyl + qsec+vs+am+carb, data = mtcars)
# the order you want them
categories <- c("cyl","qsec","am","carb")
margins_lm <- margins(fit,variables=categories)

df <- summary(margins_lm)
df <- df[match(categories,df$factor),]
LIMITS <- range(c(df$AME+df$SE,df$AME-df$SE))
plot(NULL,xlim=c(1,nrow(df)),ylim=LIMITS,xaxt='n',
xlab="",ylab="Average Marginal Effect")
with(df,points(1:nrow(df),AME,pch=20))
with(df,segments(x0 = 1:nrow(df),y0=AME-SE,y1=AME+SE))
axis(1, at=1:length(categories), labels=categories, 
las = 2, cex.axis = 0.8)

在此处输入图像描述

或者简单地使用上面的 df,并应用 ggplot2:

ggplot(df,aes(x=factor,y=AME)) + 
geom_point() + 
geom_segment(aes(y=lower,yend=upper,x=factor,xend=factor)) + 
theme_bw() + 
scale_x_discrete(limits=categories)

在此处输入图像描述


推荐阅读