【问题标题】:Creating a bar chart with ggplot2 with dummy variables on x-axis as well as providing the y-values for the barplot使用 ggplot2 创建一个条形图,x 轴上有虚拟变量,并为条形图提供 y 值
【发布时间】:2020-11-09 03:43:30
【问题描述】:

我的数据集有两个变量来描述我的观察结果:

  1. 变量“1978 年的收入”
  2. “治疗状态”的虚拟变量 0 或 1(在治疗组或对照组中)。

我现在的目标是创建一个条形图,描述 1978 年治疗组和对照组的平均收入。 我现在的代码: chart1 = ggplot(data = NSW, aes(x = treatment, y = income)) + geom_bar(stat='identity')

我得到的是:enter image description here

我将代码更改为:chart1 = ggplot(data = NSW, aes(x = treatment, y = mean(income))) + geom_bar(stat='identity')

生成此条形图的工具:enter image description here

我只是不知道如何告诉 R 我希望两个条在 y 轴上“停止”,其中描述了任一组各自的平均收入。

编辑: 这就是最终结果的样子(抱歉我画得不好): enter image description here 图表的标题可能是:1978 年的平均收入——治疗组和对照组

希望任何人都可以在这里帮助我。 谢谢!

PS:不要混淆,在两个条形图中,收入的变量名称都标记为“re78”。

【问题讨论】:

  • 这对我来说没有意义:“我只是对如何告诉 R 我希望两个条在 y 轴上“停止”感到困惑,其中任何一个的各自平均收入组正在被描述”
  • 更新了我原来的帖子。希望我的图能更清楚。再次感谢!
  • 请使用dput 或我们可以复制和使用的东西添加数据。还显示共享数据的预期输出。了解how to ask a good questionhow to give a reproducible example

标签: r ggplot2 bar-chart data-visualization


【解决方案1】:

这是你想要的吗?

# Load libraries
library(ggplot)

# Create some fake data
income <- runif(n = 10, min = 0, max = 30000)
cohort <- factor(sample(x = 0:1, size = 10, replace = TRUE),
                    labels = c("control", "treatment"))
NSW <- data.frame(income, cohort)

# Plot the data
chart1 = ggplot(data = NSW, aes(x = cohort, y = income)) +
  geom_bar(stat = "summary", fun = "mean") +
  scale_y_continuous(labels=scales::dollar_format(),
                     expand = c(0, 0), name = "Mean Income")
chart1

【讨论】:

    猜你喜欢
    • 2019-11-28
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 2020-04-20
    • 1970-01-01
    • 2019-02-15
    相关资源
    最近更新 更多