我正在使用一个数据集,其中包括一个连续变量(我们称之为 z)和两个代表不同条件的分类变量(x 和 y)。我想创建一个图表,使我能够直观地看到 z 如何随时间变化,同时还突出显示基于 x 和 y 条件的差异。 具体来说,我希望图表显示:
z随时间的演变。
x 是 A 的条目和 x 不是 A 的条目之间的区别。
y 是 a 的条目和 y 不是 a 的条目之间的区别。 有人可以指导我如何使用 ggplot 这样的常见数据可视化工具来实现这一目标吗?
图书馆(炸药)
数据(分类示例)
这不是我的真实数据集。另外,我做了类似 this 的事情,但它只是为 x 添加了两行。
一个潜在的解决方案是:
# install.packages("dynamite")
library(dynamite)
library(tidyverse)
data(categorical_example)
categorical_example %>%
mutate(is_x_A = ifelse(x == "A", "x is A", "x is not A"),
is_y_a = ifelse(y == "a", "y is a", "y is not a")) %>%
ggplot(aes(x = time, y = z, color = interaction(is_x_A, is_y_a, sep = " & "))) +
geom_smooth() +
scale_color_hue(name = "") +
theme_bw() +
theme(legend.position = "top")
#> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'
创建于 2024-03-27,使用 reprex v2.1.0
或者也许:
# install.packages("dynamite")
library(dynamite)
library(tidyverse)
data(categorical_example)
categorical_example %>%
mutate(is_x_A = ifelse(x == "A", "x is A", "x is not A"),
is_y_a = ifelse(y == "a", "y is a", "y is not a")) %>%
ggplot(aes(x = time, y = z, color = is_x_A)) +
geom_smooth() +
scale_color_hue(name = "") +
theme_bw() +
facet_wrap(~is_y_a)
#> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'
创建于 2024-03-27,使用 reprex v2.1.0
我认为“最佳”解决方案取决于您的实际数据;这些方法可以解决您的问题吗?