Reputation: 2549
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.
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.
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
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:
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:
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:
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:
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:
Upvotes: 3