如何结合两个定性数据以制作条形图

发布于 2025-01-21 03:26:11 字数 269 浏览 1 评论 0原文

我有采访数据,我想使用 ggplot2 制作条形图。

我的数据结构如下所示: 在此处输入图像描述

如何制作条形图,如

  1. y 轴必须是计数
  2. x 轴必须是“非常好”, “好”、“不错”、“不好”、“很不好”。
  3. 每个 x 变量上方应该有两个图表(昨天和今天具有不同颜色)。
  4. 可选:我可以将每个图表按性别分开吗?

I have data from an interview and I want to make a bargraph using ggplot2.

The structure of my data looks like so:
enter image description here

How do I make a bar graph like

  1. y axis must be count
  2. x axis must be "Very good", "Good", "Not bad", "Bad", "Very bad".
  3. There should be two graphs (Yesterday and Today with differ colour) above each of x variables.
  4. Optional: Can I seperate each of graphs with gender?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绳情 2025-01-28 03:26:11

如果要制作两个图表昨天和今天在单个GGPLOT中显示(或要在同一绘图中显示两个),则需要包含一个Pivot_longer

示例数据

df <- as.data.frame(structure(c(1L, 2, 3, 4, 5, 6, "Male", "Female", "Female", 
            "Male", "Male", "Female", "Very good", "Good", "Not bad", "Bad", 
            "Very bad", NA, "Good", "Bad", "Very good", "Very bad", "Not bad", 
            NA), .Dim = c(6L, 4L), .Dimnames = list(NULL, c("id", "Gender", 
                                                            "Yesterday", "Today"))))
df
#>   id Gender Yesterday     Today
#> 1  1   Male Very good      Good
#> 2  2 Female      Good       Bad
#> 3  3 Female   Not bad Very good
#> 4  4   Male       Bad  Very bad
#> 5  5   Male  Very bad   Not bad
#> 6  6 Female      <NA>      <NA>

争吵和绘图

library(tidyverse)
library(ggplot2)

df %>% 
  pivot_longer(c(-id, -Gender)) %>% 
  ggplot(aes(x = value, fill = Gender)) +
  geom_bar() +
  facet_wrap("name")

​(v2.0.1)

If you want to make two graphs to display Yesterday and Today in a single ggplot (or want to display both in the same plot) you'll need to include a pivot_longer

Example data

df <- as.data.frame(structure(c(1L, 2, 3, 4, 5, 6, "Male", "Female", "Female", 
            "Male", "Male", "Female", "Very good", "Good", "Not bad", "Bad", 
            "Very bad", NA, "Good", "Bad", "Very good", "Very bad", "Not bad", 
            NA), .Dim = c(6L, 4L), .Dimnames = list(NULL, c("id", "Gender", 
                                                            "Yesterday", "Today"))))
df
#>   id Gender Yesterday     Today
#> 1  1   Male Very good      Good
#> 2  2 Female      Good       Bad
#> 3  3 Female   Not bad Very good
#> 4  4   Male       Bad  Very bad
#> 5  5   Male  Very bad   Not bad
#> 6  6 Female      <NA>      <NA>

Wrangling and plotting

library(tidyverse)
library(ggplot2)

df %>% 
  pivot_longer(c(-id, -Gender)) %>% 
  ggplot(aes(x = value, fill = Gender)) +
  geom_bar() +
  facet_wrap("name")

Created on 2022-04-12 by the reprex package (v2.0.1)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文