DJJ
DJJ

Reputation: 2549

align horizontally multi-word axis text label in ggplot

I have the following error_bar plot and I would like to align horizontally Latin America with Asia and Costa Rica with India in the axis-text.

edit 1:

I'm looking for an axis text in a tabular form: that is a Region column and country column. The reason is that I have much more information to represent.

error-bar_plot

tg <- ToothGrowth
setDT(tg)
aa <- tg[,.(mean=mean(len),ci95=1.96*sd(len)),supp]
aa[,country:=c("India","Costa Rica")]
aa[,region:= c("Asia","Latin America")]


ggplot(aa, aes(y=paste(region,country), x=mean)) + 
    geom_errorbar(aes(xmin=mean-ci95, xmax=mean+ci95)) +
     geom_point()

Upvotes: 0

Views: 152

Answers (1)

Duck
Duck

Reputation: 39623

Try this approach:

library(data.table)
library(datasets)
library(ggplot2)
#Code
tg <- ToothGrowth
setDT(tg)
aa <- tg[,.(mean=mean(len),ci95=1.96*sd(len)),supp]
aa[,country:=c("India","Costa Rica")]
aa[,region:= c("Asia","Latin America")]

#Plot
ggplot(aa, aes(y=paste(region,country), x=mean)) + 
  geom_errorbar(aes(xmin=mean-ci95, xmax=mean+ci95)) +
  geom_point()+
  theme(axis.text.y = element_text(angle=90,hjust=0.5))

Output:

enter image description here

Update:

#Code 2
ggplot(aa, aes(y=paste(region,'\n',country), x=mean)) + 
  geom_errorbar(aes(xmin=mean-ci95, xmax=mean+ci95)) +
  geom_point()+
  theme(axis.text.y = element_text(angle=90,hjust=0.5))

Output:

enter image description here

Update 2: A tabular form can be reached with ggtext:

library(data.table)
library(datasets)
library(ggplot2)
library(ggtext)
library(glue)
library(dplyr)
#Code
tg <- ToothGrowth
setDT(tg)
aa <- tg[,.(mean=mean(len),ci95=1.96*sd(len)),supp]
aa[,country:=c("India","Costa Rica")]
aa[,region:= c("Asia","Latin America")]

#Format data
aa %>% 
  mutate(color = c("#009E73", "#009E73"),
         name = glue("<i style='color:{color}'>{region}</i> ({country})")) -> aa

#Code 2
ggplot(aa, aes(y=name, x=mean)) + 
  geom_errorbar(aes(xmin=mean-ci95, xmax=mean+ci95)) +
  geom_point()+
  theme(axis.text.y = element_markdown())

Output:

enter image description here

You can difference by column using colors.

Update 2: You can use facets to reach something close to what you want:

#Code 3
ggplot(aa, aes(y=region, x=mean)) + 
  geom_errorbar(aes(xmin=mean-ci95, xmax=mean+ci95)) +
  geom_point()+
  facet_wrap(.~country,scales = 'free_y',strip.position='left',ncol = 1)+
  theme(strip.text.y.left = element_text(angle = 0))

Output:

enter image description here

And formating facets you can get this:

#Code 4
ggplot(aa, aes(y=region, x=mean)) + 
  geom_errorbar(aes(xmin=mean-ci95, xmax=mean+ci95)) +
  geom_point()+
  facet_wrap(.~country,scales = 'free_y',strip.position='left',ncol = 1)+
  theme(strip.text.y.left = element_text(angle = 0),
        strip.background.y = element_blank())

Output:

enter image description here

Upvotes: 3

Related Questions