在ggplot2中动态格式化各个轴标签

时间:2015-05-04 17:14:41

标签: r ggplot2

这可能最终成为calllibrary(ggplot2) data <- data.frame(labs = c("Oranges", "Apples", "Cucumbers"), counts = c(5, 10, 12)) ggplot(data = data) + geom_bar(aes(x = labs, y = counts), stat="identity")` 问题,但我试图有条件地格式化各个轴标签。

在以下示例中,我希望有选择地加粗其中一个轴标签:

theme

No Bolding

类似的问题here,但解决方案涉及element_textbreaks <- levels(data$labs) labels <- breaks labels[2] <- expression(bold("Cucumbers")) ggplot(data = data) + geom_bar(aes(x = labs, y = counts), stat="identity") + scale_x_discrete(label = labels, breaks = breaks) 。我试图直接使用轴标签。

我可以手动执行此操作,如下所示:

breaks <- levels(data$labs)
labels <- breaks
labels[2] <- expression(bold(labels[2]))

ggplot(data = data) + 
  geom_bar(aes(x = labs, y = counts), stat="identity") + 
  scale_x_discrete(label = labels, breaks = breaks)

Bolded

但是,如果我尝试通过编制索引而不是输入&#34; Cucumbers&#34;来实现,我会收到以下错误:

labels[2]

这是有道理的,因为它没有评估{{1}}。但是,有谁知道如何强迫它这样做?谢谢。

2 个答案:

答案 0 :(得分:11)

怎么样

breaks <- levels(data$labs)
labels <- as.expression(breaks)
labels[[2]] <- bquote(bold(.(labels[[2]])))

ggplot(data = data) + 
  geom_bar(aes(x = labs, y = counts), stat="identity") + 
  scale_x_discrete(label = labels, breaks = breaks)

这里我们更明确地转换为表达式,我们使用bquote()将标签的值插入表达式本身。

答案 1 :(得分:2)

另一种选择是使用breaks <- levels(data$labs) # Reference breaks by name toBold = "Cucumbers" ggplot(data = data) + geom_bar(aes(x = labs, y = counts), stat="identity") + scale_x_discrete(label = labels, breaks = breaks) + theme(axis.text.x= element_text(face=ifelse(breaks %in% toBold, "bold", "plain"))) # Reference breaks by position label.index=2 ggplot(data = data) + geom_bar(aes(x = labs, y = counts), stat="identity") + scale_x_discrete(label = labels, breaks = breaks) + theme(axis.text.x= element_text(face=ifelse(breaks %in% labels[match(label.index, 1:length(breaks))], "bold", "plain"))) 动态设置字体,但我不确定这是否比@ MrFlick的答案更好或更差:

Disallow: /*?*dir=
Disallow: /*?*order=
Disallow: /*?*p=