我需要将两个单词(Increasing / Decreasing)放置在垂直于x轴的上方和下方的条形图左侧。我尝试使用annotate
,但运气不佳。文本重叠,并且并非在所有情况下都放置正确。
将文本放在浅灰色x轴的正上方和正下方并留有足够的空间来显示单词的最佳方法是什么?可能的正值范围是0到50,负值范围是0到-50。
R脚本下有3个测试。
library("tidyverse")
red <- "#CD5C5C"
gold <- "#FCB700"
lt_grey <- "#D8D8D8"
dark_grey <- "#525250"
axis_text_size <- 16
df <- tibble(
type = c("up", "down"),
term = c("1yr", "1yr"),
value = c(3, -6),
display_value = c(3, 6),
vjust = c(-0.3, 1.2),
bar_num_col = c("#FCB700", "#C8F5C0")
)
# Stacked bar plot
ggplot(df, aes(fill = type, y = value, x = term)) +
geom_bar(position = "stack", stat = "identity") +
scale_fill_manual(values = c(red, gold)) +
labs(title = "Title") +
theme_minimal() +
theme(
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.x = element_text(size = axis_text_size),
axis.text.y = element_blank(),
panel.grid.major.x = element_line(size = 0.2, linetype = 'solid',
colour = "#696969"),
panel.grid.major.y = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.minor.y = element_blank(),
axis.ticks.y = element_blank(),
panel.background = element_rect(fill = dark_grey),
legend.position = "none"
) +
geom_text(aes(term, label = display_value, vjust = vjust, color = type), size = 8) +
scale_color_manual(values = c(red, gold)) +
# Add horizontal line
geom_hline(yintercept = 0, size = 1.5, colour = lt_grey) +
# Expand grey area above and below ends of bars to make room for the numbers. (bottom, top)
scale_y_continuous(expand = expansion(mult = c(0.1, 0.1))) +
annotate("text", x = 0.1, y = 0.3, label= "bold(Increases)",
col = gold, size = 8, angle = 90, parse = TRUE) +
annotate("text", x = 0.1, y = -0.31, label= "bold(Decreases)",
col = red, size = 8, angle = 90, parse = TRUE)
# Tests -------------------------------------------------------------------
# Test 1
df$value <- c(0, 0)
df$display_value <- c(0, 0)
# Test 2
df$value <- c(2, -5)
df$display_value = c(2, 5)
# Test 3
df$value <- c(2, -50)
df$display_value = c(2, 50)
1条答案
按热度按时间wkyowqbh1#
根据输出尺寸和文本大小,文本将占用不同的图表空间量;如果您希望在以不同大小输出时具有更高的可预测性,可以查看
ggtext
包并定义注解来填充在图表空间中定义了维度的框。