【问题标题】:Plot two box plots with same y variable but different x variables in ggplot2在ggplot2中绘制两个具有相同y变量但不同x变量的箱线图
【发布时间】:2020-12-02 07:41:51
【问题描述】:

我有一个包含 3 列的数据集。一是每月支出(y 变量)。此变量中的每个值都在两个不同的变量下分类为 1 或 0。

数据看起来像这样:

  df_UP.q234_month_exp df_UP.LFT df_UP.LF
1                   NA         0        1
2                   NA         1        1
3                12000         1        1
4                   NA         1        1
5                20000         1        1
6                   NA         0        1

数据大约有 1200 行。

我想要一个图,它为 'df_UP.q234_month_exp' 创建一个箱形图作为 'df_UP.LFT' 的所有行的 y 变量,它们是 1,并且在同一个图中使用相同的 y 变量创建另一个箱形图,但是'df_UP.LF' 的所有行都是 1。

如何使用 ggplot2 实现这一点?

【问题讨论】:

  • 你能告诉我们你到目前为止所做的尝试吗?
  • 类似的东西应该可以工作:ggplot(dat, aes(factor(f), var)) + geom_boxplot() + facet_wrap(.~g) 其中fg 是您的二进制变量,var 您的数字变量。

标签: r ggplot2 boxplot


【解决方案1】:

你可以试试这个:

library(tidyverse)
#Data
df <- structure(list(df_UP.q234_month_exp = c(NA, NA, 12000L, NA, 20000L, 
NA), df_UP.LFT = c(0L, 1L, 1L, 1L, 1L, 0L), df_UP.LF = c(1L, 
1L, 1L, 1L, 1L, 1L)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))

代码:

df %>% pivot_longer(cols = -df_UP.q234_month_exp) %>%
  filter(value==1) %>% ggplot()+
  geom_boxplot(aes(x = name,y = df_UP.q234_month_exp,color=name,group=name))

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-19
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    相关资源
    最近更新 更多