【发布时间】:2016-09-04 21:04:11
【问题描述】:
我想为图表标题中的某些字词添加颜色。我已经能够find some precedent here。具体来说,我希望用撇号(在下面的输出中)包裹的文本与它们各自条形图的颜色相对应。
这是我在将 PDF 导出到 Adobe Illustrator 或其他程序之前在 R 中使用标题的程度。
name <- c("Peter", "Gabriel", "Rachel", "Bradley")
age <- c(34, 13, 28, 0.9)
fake_graph <- family[order(family$age, decreasing = F), ]
fake_graph <- within(fake_graph, {
bar_color = ifelse(fake_graph$name == "Rachel", "blue", "gray")
})
# Plot creation
library(ggplot2)
fake_bar_charts <- ggplot() +
geom_bar(
data = fake_graph,
position = "identity",
stat = "identity",
width = 0.75,
fill = fake_graph$bar_color,
aes(x = name, y = age)
) +
scale_x_discrete(limits = fake_graph$name) +
scale_y_continuous(expand = c(0, 0)) +
coord_flip() +
theme_minimal()
family <- data.frame(name, age)
# Add title
library(grid)
library(gridExtra)
grid_title <- textGrob(
label = "I spend more time with 'Rachel' than\nwith 'other family members.'",
x = unit(0.2, "lines"),
y = unit(0.1, "lines"),
hjust = 0, vjust = 0,
gp = gpar(fontsize = 14, fontface = "bold")
)
gg <- arrangeGrob(fake_bar_charts, top = grid_title)
grid.arrange(gg)
输出:
此示例使用ggplot2 创建条形图以及grid 和gridExtra 用于标题功能,但我愿意使用任何解决方案(最好使用ggplot2 来创建图表本身) 可以为我提供引号中的文本以匹配它们各自的条形图颜色。
本网站上的任何其他解决方案都无法解决这个难题,但我很想在 R 中找到解决方案。
感谢您的帮助!
【问题讨论】:
标签: r ggplot2 gridextra r-grid