Reputation: 4010
I currently have the following R code, and was wondering if its possible to selectively bold/italicize/apply other styles the labels on the axis
> w1 <- read.csv(file="test1.csv",sep=",", head=TRUE)
> w1$Commits <- w1$normal + w1$merges
> w1
Commits normal merges
John 4 3 1
Sarah 19 13 6
Zach 3 3 0
Jacob 27 24 3
> titles <- w1$merges / w1$Commits
> titles <- sprintf("%s%%", format(round(titles * 100), 1))
> bp <- barplot(rbind(w1$normal, w1$merges), main="Playing with R", xlab="Who", names.arg=rownames(w1), col=c("blue", "red"), ylim = c(0,30))
> text(bp, rbind(w1$Commits), labels = titles, pos = 3, cex = 0.75)
This produces a nice barchart (I could probably have used %d instead of format but thats not important), exactly how I want it, however I also want to be able to make the names.arg list styled, so that at the bottom I can, for example see the labels:
John Sarah Zach Jacob
Is there a way to apply styles to these labels? Or some other way to mark some bars as different (gray background, etc)?
Upvotes: 0
Views: 568
Reputation: 263342
bp <- barplot(rbind(w1$normal, w1$merges),
main="Playing with R", xlab="Who", names.arg=rep("",4),
col=c("blue", "red"), ylim = c(0,30))
text(bp, rbind(w1$Commits), labels = titles, pos = 3, cex = 0.75)
axis(1, at=bp, labels= parse(text=
gsub("\\s", '~', paste0(c("bold(", "", "italic(", ""),
rownames(w1),
c( ")", "", ")", "")
) )
) )
This seems rather kludgy, but you should have seem my failed efforts at making a length 4 expression vector with
expression
, bquote
, and substitute
.
Upvotes: 1
Reputation: 115392
Here is an approach using bquote
(and do.call
)
# the order in which you want the "bolding"
xx <- expression(bold(.(x)), italic(.(x)), .(x), .(x))
# a list of lists containing the information for bquote
xL <- lapply(rownames(w1), function(x) list(x=x))
# using Map and do.call and as.expression to create the list of expressions
labs <- as.expression(Map(function(expr,where) {do.call(bquote, list(expr,where))},
expr = xx, where =xL))
bp <- barplot(rbind(w1$normal, w1$merges),
main="Playing with R", xlab="Who", names.arg=rep("",4),
col=c("blue", "red"), ylim = c(0,30))
text(bp, rbind(w1$Commits), labels = titles, pos = 3, cex = 0.75)
axis(1, at=bp, labels= labs)
Or similarly using substitute
xs <- expression(bold(x), italic(x), x, x)
labs <- Map(function(expr,where) {do.call(substitute, list(expr,where))}, expr = xs, where =xL)
Upvotes: 2