llewmills
llewmills

Reputation: 3568

True Minus Sign On X-axis Variable Labels in ggplot2

I am looking for a way to get a true minus sign into a graph in ggplot2.

Generate data:

score <- c(rnorm(8, 20, 3), rnorm(8, 35, 5))
gene <- factor((rep(c(1,2), each = 8)))
df <- data.frame(gene, score)

Now rename factor with a name that includes a minus sign

require(plyr)

df$gene <- mapvalues(df$gene, from = c(1,2), to = c("Gene -", "Gene +"))

Now graph the dataframe in ggplot2

cellMeansDF <- aggregate(score ~ gene, df, mean)

require(ggplot2)

plot1 <- ggplot(cellMeansDF, aes(gene, score)) +
         geom_bar(stat = "identity", position = "dodge", size = 0.1) + 
         xlab("") + 
         theme(axis.text.x = element_text(face = "plain", color = "black", size = 15))

plot1

Now notice the minus sign is not wide enough. It is really a dash. How do I get ggplot2 to display a true minus sign? Even an en dash would do.

Upvotes: 2

Views: 2073

Answers (2)

eipi10
eipi10

Reputation: 93871

You can use the Unicode en dash character instead of a hyphen:

"Gene \u2013"

Which gives:

"Gene –"  

Whereas the standard hyphen looks like this:

"Gene -"

So, change the hyphen to an en dash in your code:

df$gene <- mapvalues(df$gene, from = c(1,2), to = c("Gene \u2013", "Gene +"))

To get the following plot:

enter image description here

Upvotes: 4

Hack-R
Hack-R

Reputation: 23211

How about this? You can of course take or leave the bold according to your preference.

score <- c(rnorm(8, 20, 3), rnorm(8, 35, 5))
gene <- factor((rep(c(1,2), each = 8)))
df <- data.frame(gene, score)


require(plyr)

df$gene <- mapvalues(df$gene, from = c(1,2), to = c("Gene -", "Gene +"))

Now graph the dataframe in ggplot2

cellMeansDF <- aggregate(score ~ gene, df, mean)

require(ggplot2)

plot1 <- ggplot(cellMeansDF, aes(gene, score)) +
  geom_bar(stat = "identity", position = "dodge", size = 0.1) + 
  xlab("") + 
  theme(axis.text.x = element_text(family="mono", face="bold", color = "black", size = 15))

plot1

Plot

You can find a complete list of fonts here: http://www.cookbook-r.com/Graphs/Fonts/

The font and other element_text options will determine how this character displays. Here's a graphic summary of your font choices:

Fonts

Upvotes: 0

Related Questions