将第二个字符轴添加到 ggplot2
Add second character axis to ggplot2
我希望将语义差异分数的用户调查结果呈现为箱线图,其中第一个语义沿默认 x 轴显示,第二个语义沿辅助顶部 x 轴显示。简单来说,这可以表示为
df <- data.frame(sem1 = c("good", "big", "red"), sem2 = c("bad", "small", "blue"), a = c(4,6,1), b = c(6,2,6), c = c(8,3,7))`
df %>% pivot_longer(!c(sem1, sem2), names_to = "user", values_to = "score") %>%
ggplot() +
geom_boxplot(aes(x = sem1, y = score)) +
ylim(1,10)
生成以下图表。我真正想做的是将 sem2 中的字符(即“坏”、“小”、“蓝色”)添加到图表顶部的辅助轴。我所看到的使用 sec_axis 的所有内容似乎都适合数字轴的转换,而不是添加不同的第二个轴。我相信我可以使用 annotation_custom 一个一个地添加每个语义,但在我的实际应用程序中,使用 ~15 个语义对来显示这可能会变得非常麻烦。有没有更优雅的方式?
一个可能的选择:
library(tidyverse)
df <- data.frame(sem1 = c("good", "big", "red"),
sem2 = c("bad", "small", "blue"),
a = c(4, 6, 1), b = c(6, 2, 6),
c = c(8, 3, 7)) %>%
pivot_longer(!c(sem1, sem2), names_to = "user", values_to = "score")
df %>%
ggplot(aes(sem1, score)) +
geom_boxplot() +
geom_label(aes(y = max(score * 1.2), label = sem2)) +
ylim(1, 10)
由 reprex package (v2.0.1)
于 2022-05-19 创建
我希望将语义差异分数的用户调查结果呈现为箱线图,其中第一个语义沿默认 x 轴显示,第二个语义沿辅助顶部 x 轴显示。简单来说,这可以表示为
df <- data.frame(sem1 = c("good", "big", "red"), sem2 = c("bad", "small", "blue"), a = c(4,6,1), b = c(6,2,6), c = c(8,3,7))`
df %>% pivot_longer(!c(sem1, sem2), names_to = "user", values_to = "score") %>%
ggplot() +
geom_boxplot(aes(x = sem1, y = score)) +
ylim(1,10)
生成以下图表。我真正想做的是将 sem2 中的字符(即“坏”、“小”、“蓝色”)添加到图表顶部的辅助轴。我所看到的使用 sec_axis 的所有内容似乎都适合数字轴的转换,而不是添加不同的第二个轴。我相信我可以使用 annotation_custom 一个一个地添加每个语义,但在我的实际应用程序中,使用 ~15 个语义对来显示这可能会变得非常麻烦。有没有更优雅的方式?
一个可能的选择:
library(tidyverse)
df <- data.frame(sem1 = c("good", "big", "red"),
sem2 = c("bad", "small", "blue"),
a = c(4, 6, 1), b = c(6, 2, 6),
c = c(8, 3, 7)) %>%
pivot_longer(!c(sem1, sem2), names_to = "user", values_to = "score")
df %>%
ggplot(aes(sem1, score)) +
geom_boxplot() +
geom_label(aes(y = max(score * 1.2), label = sem2)) +
ylim(1, 10)
由 reprex package (v2.0.1)
于 2022-05-19 创建