r - R 结构化数据以允许并排比较
问题描述
在 R 中,您如何在单个图表中比较计划使用和实际使用?
我可以显示计划使用的条形图或实际使用的条形图,但我不知道如何显示在实际旁边显示计划的条形图
我有以下数据表。
房间 | 托德 | 预定使用 | 实际使用 |
---|---|---|---|
一种 | 早晨 | 37.5 | 22.3 |
一种 | 下午 | 27 | 15.3 |
一种 | 晚上 | 6.3 | 2 |
乙 | 早晨 | 18 | 24 |
乙 | 下午 | 27 | 27 |
乙 | 晚上 | 6.5 | 12.3 |
C | 早晨 | 15.8 | 7.5 |
C | 下午 | 20 | 10.3 |
C | 晚上 | 12.8 | 18 |
D | 早晨 | 10 | 7.5 |
D | 下午 | 10 | 7.5 |
D | 晚上 | 18 | 12.3 |
这就是我绘制计划使用的方式,并带有一个绘图示例。
# Read the csv data
x <- read.csv("C:/Users/David/Desktop/R-ggplot.csv")
View(x)
# Re-level to show on facet as: Morning, Afternoon, Evening
# insteat of: Afternoon, Evening, Morning
x$ToD <- factor(x$ToD, levels = c("Morning",
"Afternoon",
"Evening"))
# Plot the graph
y <- ggplot(data = x, aes(x = `Room`,
y = `Scheduled.Use`,
fill = `ToD`)) +
geom_bar(position='dodge', stat='identity') +
facet_wrap(~`ToD`, nrow = 3) +
ggtitle("Room Scheduled Use v. Actual Use") +
ylab("Scheduled v. Acutual")
plot(y)
解决方案
ggplot 希望它是“长”格式,所以你需要先 pivot_longer。当您旋转到更长的时间时,被旋转的列的名称将变为一个名为“name”的新列,该列的值将变为一个名为“value”的列(请查看管道链第一部分的输出在 pivot_longer 之后看看我的意思)。如果您希望列以不同的顺序排列,您需要将“名称”转换为因子并按您想要的顺序指定级别。
x <- read.delim(text = '
Room ToD Scheduled.Use Actual.Use
A Morning 37.5 22.3
A Afternoon 27 15.3
A Evening 6.3 2
B Morning 18 24
B Afternoon 27 27
B Evening 6.5 12.3
C Morning 15.8 7.5
C Afternoon 20 10.3
C Evening 12.8 18
D Morning 10 7.5
D Afternoon 10 7.5
D Evening 18 12.3
')
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(tidyr)
library(ggplot2)
sched_act_plot <-
x %>%
mutate(across(ToD, factor, levels = c("Morning",
"Afternoon",
"Evening"))) %>%
pivot_longer(c(Scheduled.Use, Actual.Use)) %>%
mutate(across(name, factor, levels = c('Scheduled.Use',
'Actual.Use'))) %>%
ggplot(aes(x = Room, y = value, fill = name)) +
geom_bar(position = 'dodge', stat = 'identity') +
facet_wrap(~ToD, nrow = 3) +
ggtitle("Room Scheduled Use v. Actual Use") +
ylab("Scheduled v. Acutual")
plot(sched_act_plot)
由reprex 包创建于 2021-05-16 (v2.0.0 )
推荐阅读
- xaml - xamarin 在 CollectionView 中形成更新项目
- c++ - 显示前 3 个项目
- node.js - 如何使用云函数中的 OrderByChild() 对 Datasnapshot 进行排序
- java - 如何让程序打印它的位置?
- android - 将自定义声音文件放在 Ionic 4 上的 OneSignal 推送通知的什么位置?
- java - 如何使用输入使我制作的简笔画移动?
- python - 限制发送的短信数量
- javascript - 在函数中使用 this 关键字设置属性
- sparql - 使用 SPARQL DBPEDIA 获取地名中的每个地名
- powershell - 如何增加引号中的数组的索引?