Align text right justified but center of each box in geom_text

4.7k views Asked by At

I have created a graph with ggplot using geom_tile and geom_text. I want to be able to read the numbers down one column and have them all lineup. I set the font to Courier and used hjust to justify the numbers (otherwise the negative sign throws off the alignment). However I cant find a way to keep this right justification and center the text in the middle each box. Any ideas on how to get the numbers to line up so you can scan a column quickly?

Reproducible example below.

require(reshape2)
require(ggplot2)
require(scales)

set.seed(504)
df_graph <- data.frame("Category"=c("Green","Blue","Red","Yellow","Black","Random1","Random2","Random3","Random4","Random5","Random6","Random7",
                                    "Random8","Random9","Random10"),"Test1"=rnorm(15),"Test1"=rnorm(15),"Test2"=rnorm(15),"Test3"=rnorm(15),
                       "Test4"=rnorm(15),"Test5"=rnorm(15))

df_graph <- melt(df_graph)                       
df_graph$text <- round(df_graph$value, 2)

colors_used <- c("#B2182B","#D6604D","#F4A582","#FDDBC7","#F7F7F7","#D1E5F0","#92C5DE","#4393C3","#2166AC")
values <- seq(-4, 4, length = 9)

g <- ggplot(df_graph, aes(variable, Category))
g <- g + geom_tile(aes(fill = value), colour = "white", size=0.75)
g <- g + geom_text(aes(label=text),size=3, family="Courier", hjust = 1)
g <- g + scale_fill_gradientn(colours = colors_used, na.value = "#FFFFFF", values = values,rescaler = function(x, ...) x, oob = identity)
g <- g + theme_bw()
g <- g + theme(
  axis.text.x= element_text(color="black", size=10, angle = 45, hjust = 0.5),
  axis.text.y= element_text(color="black", size=8),
  axis.title.y = element_text(color="black",size=10),
  plot.title = element_text(color="black",size=14,face="bold"),
  legend.key = element_rect(fill="white"), legend.background = element_rect(fill=NA),
  legend.position="none",
  legend.title = element_blank(),
  panel.grid  = element_blank(),
  panel.border = element_blank()
)
1

There are 1 answers

2
rcs On BEST ANSWER

Use hjust=0.5 in geom_text() and pad the labels for positive numbers appropriately, i.e. prepend space characters to obtain labels of equal length:

df_graph$text <- format(round(df_graph$value, 2))

plot