我正在尝试使用以下结构可视化序数数据:
library(ggdist)
library(ggplot2)
library(dplyr)
data(long_data)
srss_question1 <- long_data %>%
filter(type == "1") %>%
dplyr::select(id, day, response)
head(srss_question1)
# A tibble: 6 × 3
id day response
<dbl> <fct> <dbl>
1 1 day7 5
2 1 day2 4
3 1 day0 3
4 2 day7 5
5 2 day2 5
6 2 day0 6
绘制没有颜色的图形的代码,按预期工作:
srss_question1 %>%
ggplot(aes(y = response, x = day)) +
stat_slab(
data = filter(srss_question1, day == "day7"),
density = "histogram",
breaks = breaks_fixed(width = 0.5),
align = "center",
position = position_nudge(x = 0),
side = "right"
) +
stat_slab(
data = filter(srss_question1, day == "day2"),
density = "histogram",
breaks = breaks_fixed(width = 0.5),
align = "center",
position = position_nudge(x = 0),
side = "right"
) +
stat_slab(
data = filter(srss_question1, day == "day0"),
density = "histogram",
breaks = breaks_fixed(width = 0.5),
align = "center",
position = position_nudge(x = 0),
side = "right",
) +
geom_line(
aes(group = id),
size = 0.25,
position = position_jitter(h = 0.05, w = 0.05),
alpha = 0.25
) +
scale_y_continuous(limits = c(-0.25, 7.5), breaks = 0:10) +
labs(x = "Day", y = "Question 1 Responses") +
theme_bw()
产生这个数字: 图灰色
我想看看将 Viridis 调色板映射到该图是否有助于可视化,并在此处对其进行了编码:
srss_question1 %>%
ggplot(aes(x = day, y = response, fill = factor(response))) +
stat_slab(
data = filter(srss_question1, day == "day7"),
density = "histogram",
breaks = breaks_fixed(width = 0.5),
align = "center",
side = "right",
position = position_nudge(x = 0)
) +
stat_slab(
data = filter(srss_question1, day == "day2"),
density = "histogram",
breaks = breaks_fixed(width = 0.5),
align = "center",
side = "right",
position = position_nudge(x = 0)
) +
stat_slab(
data = filter(srss_question1, day == "day0"),
density = "histogram",
breaks = breaks_fixed(width = 0.5),
align = "center",
side = "right",
position = position_nudge(x = 0)
) +
geom_line(
aes(group = id),
linewidth = 0.25,
position = position_jitter(h = 0.05, w = 0.05),
alpha = 0.25
) +
scale_fill_viridis_d(option = "D", direction = 1) +
scale_y_continuous(limits = c(-0.25, 7.5), breaks = 0:10) +
labs(x = "Day", y = "Question 1 Responses") +
theme_bw()
但这会从图中删除条形,如下所示: 人物颜色
将调色板映射到图形时,为什么我的 stat_slab 条消失了?非常感谢任何有关如何修复代码的见解:)
如果需要更多信息,请告诉我。
问题是你的 y 轴是连续的,当你尝试用离散值(因子)填充时,你的条形宽度变为 0。如果你用
fill
替换 colour
美学(也是相应的规模)。
另一方面,对于这种类型的几何图形,您不能使用离散 y 轴。如果您想要宽条,您可能需要考虑其他方式来绘制它,使用
geom_bar
或 geom_rect
。