我想按轴分割下面图的图例。一个用于“班级”、“性别”、“年龄”和“幸存者”。
library(ggforce)
?geom_parallel_sets
data <- reshape2::melt(Titanic)
data <- gather_set_data(data, 1:4)
ggplot(data, aes(x, id = id, split = y, value = value)) +
geom_parallel_sets(aes(fill = Class), alpha = 0.3, axis.width = 0.1) +
geom_parallel_sets_axes(aes(fill=y), axis.width = 0.1) +
geom_parallel_sets_labels(colour = 'white') +
scale_x_discrete(limits = c("Class", "Sex", "Age", "Survived"), expand = c(0, 0)) +
theme(
panel.background = element_blank(),
axis.ticks.y = element_blank(),
axis.text.y = element_blank(),
axis.title.x = element_blank()
)
我研究了文档示例但没有成功。
根据您的评论,要省略某些图例项而不影响绘图,您可以使用
scale_fill_manual
和 guide = guide_legend(...)
来抑制相关的图例键和标签。请注意,因为您的变量是因子,所以需要 as.character()
来返回文本值。
首先,创建十六进制颜色和标签向量:
library(ggforce)
# Return vector of legend values
unique_vars <- unique(unlist(data[,c("Class", "Sex", "Age", "Survived")]))
# Create vector of hex colour values for all legend items with
# colours to match default ggplot2 colours
legend_col <- scales::hue_pal()(length(unique_vars))
省略“否”和“是”:
ggplot(data, aes(x, id = id, split = y, value = value)) +
geom_parallel_sets(aes(fill = Class), alpha = 0.3, axis.width = 0.1) +
geom_parallel_sets_axes(aes(fill = y), axis.width = 0.1) +
geom_parallel_sets_labels(colour = 'white') +
scale_x_discrete(limits = c("Class", "Sex", "Age", "Survived"), expand = c(0, 0)) +
scale_fill_manual(
values = scales::hue_pal()(10),
labels = c(as.character(unique_vars[1:8]), "", ""),
guide = guide_legend(override.aes = list(fill = c(legend_col[1:8], NA, NA)))
) +
theme(
theme(legend.key = element_rect(fill = NA, color = NA)),
panel.background = element_blank(),
axis.ticks.y = element_blank(),
axis.text.y = element_blank(),
axis.title.x = element_blank()
)
省略“儿童”和“成人”:
ggplot(data, aes(x, id = id, split = y, value = value)) +
geom_parallel_sets(aes(fill = Class), alpha = 0.3, axis.width = 0.1) +
geom_parallel_sets_axes(aes(fill = y), axis.width = 0.1) +
geom_parallel_sets_labels(colour = 'white') +
scale_x_discrete(limits = c("Class", "Sex", "Age", "Survived"), expand = c(0, 0)) +
scale_fill_manual(
values = scales::hue_pal()(10),
labels = c(as.character(unique_vars[1:6]), as.character(unique_vars[9:10]), "", ""),
guide = guide_legend(override.aes = list(fill = c(legend_col[1:6], legend_col[9:10], NA, NA)))
) +
theme(
theme(legend.key = element_rect(fill = NA, color = NA)),
panel.background = element_blank(),
axis.ticks.y = element_blank(),
axis.text.y = element_blank(),
axis.title.x = element_blank()
)