我想按轴隐藏下面图例的某些部分。换句话说,抑制“类别”、“性别”、“年龄”和“幸存者”的图例项目。
library(ggforce)
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 (as in your example plot)
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(
name = "Variables",
values = legend_col,
labels = c(as.character(unique_vars[1:8]), "", ""),
guide = guide_legend(override.aes = list(fill = c(legend_col[1:8], NA, NA)))
) +
theme(
legend.key = element_rect(fill = NA, colour = 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(
name = "Variables",
values = legend_col,
labels = c(as.character(unique_vars[c(1:6, 9:10)]), "", ""),
guide = guide_legend(override.aes = list(fill = c(legend_col[c(1:6, 9:10)], NA, NA)))
) +
theme(
legend.key = element_rect(fill = NA, colour = NA),
panel.background = element_blank(),
axis.ticks.y = element_blank(),
axis.text.y = element_blank(),
axis.title.x = element_blank()
)