我使用 geom_text 在条形区域内放置一些文本,但我发现有时文本会超出条形区域,见下文。我想让文本以 substring = original_text[i:] 的形式成为原始文本的子字符串,其中自动选择 i 以便子字符串可以放入条形区域。例如:如果“ABCDEFGHIJKIFG”太长而无法放入条形区域,则条形内的文本将为所有条形显示“JKIFG”。图形图像
ordering <- c(1,2,1,2)
year <- c(2000,2000,2001,2001)
value <- c(1,10,2,10)
label <- c('ABCDEFGHIJKIFG','ABCDEFGHIJKIFG','ABCDEFGHIJKIFG','ABCDEFGHIJKIFG')
df <- data.frame("ordering" = ordering, "year" = year,'value' = value,'label' = label)
library(ggstance)
library(ggplot2)
library(gganimate)
ggplot(df, aes(y = ordering, x = value)) +
geom_barh(stat = "identity") +
geom_text(aes(x = 0, label = paste(label, " ")), vjust = 0.2, hjust = 0,color='red') +
transition_states(year, transition_length = 2, state_length = 0) +
view_follow(fixed_y = TRUE)
这是我想到的一些技巧:如果您将绘图背景设置为固定颜色,则可以在文本顶部绘制一个条以将其覆盖。它并不完美,但确实可以防止文本显示在栏外:
max_val = max(df$value)
ggplot(df, aes(y = ordering, x = value)) +
geom_barh(stat = "identity") +
geom_text(aes(x = 0, label = label), vjust = 0.2, hjust = 0,color='red') +
geom_rect(aes(xmin = value, xmax=max_val, ymin = ordering - 0.2, ymax = ordering + 0.2),
fill = "#aaaaaa") +
transition_states(year, transition_length = 2, state_length = 0) +
view_follow(fixed_y = TRUE) +
theme(panel.background = element_rect(fill = "#aaaaaa"),
panel.grid = element_blank())
编辑:经过更多思考,我想出了一个更接近您的原始意图的版本,将标签贴在栏的右侧,并使标签在左侧消失:
ggplot(df, aes(y = ordering, x = value)) +
geom_barh(stat = "identity") +
geom_text(aes(x = value, label = label), vjust = 0.2, hjust = 1, color='red') +
geom_rect(aes(xmin = -2, xmax=0, ymin = ordering - 0.2, ymax = ordering + 0.2),
fill = "grey92") +
transition_states(year, transition_length = 2, state_length = 0) +
# Manually setting limits, not ideal
coord_cartesian(xlim = c(0, 10)) +
theme(panel.background = element_rect(fill = "grey92"))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句