You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中调整因子水平,让两图中var从上到下为no、yes

调整R中因子水平顺序,实现图表var从上到下为"no"→"yes"

方式一:提前修改数据中的因子水平(推荐)

直接在数据预处理阶段锁定var的水平顺序,这样所有基于该数据的图表都会自动遵循这个顺序:

library(tidyverse)

# 假设你的数据框叫df,重新定义var的因子水平
df <- df %>%
  mutate(var = factor(var, levels = c("no", "yes")))

用levels(df$var)可以快速验证水平顺序是否正确。

方式二:绘图时临时指定顺序

如果不想改动原始数据,可在绘图的映射中直接调整:

李克特图(ggstats::gglikert)

library(ggstats)
library(patchwork)

likert_plot <- gglikert(df, aes(y = fct_relevel(var, "no", "yes"), x = your_response_var)) +
  # 你的其他绘图设置(比如主题、标签等)
  labs(title = "李克特图") +
  theme_minimal()

柱状图

bar_plot <- ggplot(df, aes(y = fct_relevel(var, "no", "yes"), x = your_count_var)) +
  geom_bar(stat = "identity") +
  # 你的其他绘图设置
  labs(title = "柱状图") +
  theme_minimal()

关键说明

因为你是垂直方向展示因子(从上到下),因子水平的第一个值会显示在图表最上方,第二个值在下方,所以设置levels = c("no", "yes")刚好能实现你要的顺序。最后用patchwork合并两个图即可:

likert_plot + bar_plot

内容的提问来源于stack exchange,提问作者Homer Jay Simpson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 13:32:19