在ggplot2中动态格式化各个轴标签 [英] Dynamically formatting individual axis labels in ggplot2
问题描述
这最终可能是一个表达式
或 call
问题,但我试图有条件地格式化各个轴标签。
在下面的例子中,我想选择加粗一个轴标签:
library(ggplot2)
data < - data.frame(labs = c(Oranges,Apples,Cucumbers),counts = c(5,
ggplot(data = data)+
geom_bar(aes(x = labs,y = counts),stat =identity)`
有类似的问题 here ,但解决方案包含主题
和 element_text
。我正在尝试直接使用轴标签。
我可以手动完成,如下所示:
breaks< - 表达式(粗体(黄瓜))
ggplot(数据=数据) - 水平(数据$实验室)
标签< - 中断
标签[2] +
geom_bar(aes(x = labs,y = counts),stat =identity)+
scale_x_discrete(label = labels,breaks = breaks)
但是,如果我试图通过索引而不是输入Cucumbers来实现,则会出现以下错误:
break < - 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)
有道理,因为它不会评估标签[2]
。但是,有没有人知道如何强迫它这样做?谢谢。
> break( - 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 =标签,休息时间=休息时间)
这里我们对转换为表达式更加明确,我们使用 bquote()
将标签的值插入表达式本身。
This may end up being an expression
or call
question, but I am trying to conditionally format individual axis labels.
In the following example, I'd like to selectively bold one of the axis labels:
library(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")`
There is similar problem here, but the solution involves theme
and element_text
. I am trying to use axis labels directly.
I can do this manually as below:
breaks <- 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)
But, if I try to do it by indexing instead of typing out "Cucumbers", I get the following error:
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)
Which makes sense, because it is not evaluating the labels[2]
. But, does anyone know how to force it to do that? Thanks.
How about
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)
Here we are more explicit about the conversion to expression and we use bquote()
to insert the value of the label into the expression itself.
这篇关于在ggplot2中动态格式化各个轴标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!