Sana Ali
Sana Ali

Reputation: 185

geom_text overlapping text and alignment of text in ggplot2

I have to draw table like look through geom_text() and i have tried using position_jitter /dodge and hjust to make it look like a table and to change text being overlapped or arranged in a oblique manner.

Here is a sample code :

require(ggplot2)
require(reshape2)

dia3 <- melt(CO2, id = c(colnames(CO2)[1],colnames(CO2)[2]))
dia3

p <- ggplot(dia3, aes_string(x=colnames(dia3)[2],y=colnames(dia3)[1],color = colnames(dia3)[3]))+
  geom_text(aes_string(label = colnames(dia3)[4]),
           position=position_dodge(width = 0.5),
            hjust = 0.5,
            size = 2.5
  )+
  scale_x_discrete(drop = TRUE)+
  theme_bw()+
  theme(
    axis.ticks.x = element_blank(),
    axis.text.y= element_text(color="black", size=8),
    axis.title.y = element_blank(),
    axis.title.x = element_blank(),
    legend.key = element_rect(fill="white"), legend.background = element_rect(fill=NA),
    legend.position="bottom",
    legend.title = element_blank(),
    panel.grid  = element_blank(),
    panel.border = element_blank()
  )
p

It produces plot like : enter image description here

I need help with arranging all the text aligned in vertically straight lines.

Thanks

Upvotes: 0

Views: 1898

Answers (1)

Axeman
Axeman

Reputation: 35402

The dodging is done by group, which is automatically set to any factor variables you have mapped, which includes x in this case. Override the default to fix the problem:

ggplot(dia3, aes_string(x = colnames(dia3)[2], y = colnames(dia3)[1], 
                        color = colnames(dia3)[3], group = colnames(dia3)[3]))+
    geom_text(aes_string(label = colnames(dia3)[4]),
              hjust = 0.5,
              size = 2.5,
              position = position_dodge(0.5)) +
    scale_x_discrete(drop = TRUE)

enter image description here

Upvotes: 1

Related Questions