在ggplot中将多字轴的文本标签水平对齐

时间:2020-09-08 21:22:16

标签: r ggplot2

我有以下error_bar图,我想在轴向文本中将拉丁美洲与亚洲水平对齐,将哥斯达黎加与印度水平对齐。

编辑1:

我正在寻找表格形式的轴文本:即“地区”列和“国家/地区”列。原因是我有更多要代表的信息。

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()

1 个答案:

答案 0 :(得分:3)

尝试这种方法:

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))

输出:

enter image description here

更新

#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))

输出:

enter image description here

更新2:可以通过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())

输出:

enter image description here

您可以使用颜色按列进行区别。

更新2:您可以使用构面来达到您想要的目标:

#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))

输出:

enter image description here

格式化方面可以得到:

#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())

输出:

enter image description here