我正在使用 ggsankey 制作桑基图,当标签重叠在节点上时,我很难让标签可见。我有三个节点,想要移动左侧的标签,这样它就不会与节点重叠,而是位于节点的左侧。我希望中间的节点保持在节点的中心,并且我想移动右侧的标签,以便位于右侧节点的右侧。
我可以使用 geom_sankey_label 和 hjust 让所有标签移动位置,但我无法弄清楚如何分别移动每个节点上的标签。我什至不知道是否可以做我想做的事。
我的代码与此非常相似-
df <- mtcars %>%
make_long(cyl, vs, am, gear, carb)
ggplot(df, aes(x = x, next_x = next_x, node = node, next_node = next_node, fill = factor(node), label = node)) +
geom_sankey(flow.alpha = .6,
node.color = "gray30",
space = 20) +
geom_sankey_label(size = 3,
color = "white",
fill = "gray40",
hjust = 0,
position = position_nudge(x = 0.1),
space = 20) +
scale_fill_viridis_d() +
theme_sankey(base_size = 18) +
labs(x = NULL) +
theme(legend.position = "none",
plot.title = element_text(hjust = .5)) +
ggtitle("Car features")
实现所需结果的一个选项是有条件地微调标签并使用例如设置标签的对齐方式。
dplyr::case_when
里面aes()
。为了微调标签的位置,我使用 ggplot2::stage()
:
library(ggplot2)
library(ggsankey)
df <- mtcars |>
make_long(cyl, vs, am, gear, carb)
ggplot(df, aes(
x = x, next_x = next_x,
node = node, next_node = next_node,
fill = factor(node), label = node
)) +
geom_sankey(
flow.alpha = .6,
node.color = "gray30",
space = 20
) +
geom_sankey_label(
aes(
# Shift labels conditional on position
x = stage(x,
after_stat = x + .1 *
dplyr::case_when(
x == 1 ~ -1,
x == 5 ~ 1,
.default = 0
)
),
# Align labels conditional on position
hjust = dplyr::case_when(
x == "cyl" ~ 1,
x == "carb" ~ 0,
.default = .5
)
),
size = 3,
color = "white",
fill = "gray40",
space = 20
) +
scale_fill_viridis_d() +
theme_sankey(base_size = 18) +
theme(
legend.position = "none",
plot.title = element_text(hjust = .5)
) +
labs(x = NULL, title = "Car features")