在X轴的左侧和右侧添加自定义标签-R ggplot2

时间:2020-05-12 23:14:46

标签: r ggplot2

我想在下面的R.代码中向我的绘图添加一些自定义标签,以创建原始绘图(在互联网上找到示例)。

library(ggplot2)
theme_set(theme_bw())  
data("mtcars")  # load data
mtcars$`car name` <- rownames(mtcars)  # create new column for car names
mtcars$mpg_z <- round((mtcars$mpg - mean(mtcars$mpg))/sd(mtcars$mpg), 2)  # compute normalized mpg
mtcars$mpg_type <- ifelse(mtcars$mpg_z < 0, "below", "above")  # above / below avg flag
mtcars <- mtcars[order(mtcars$mpg_z), ]  # sort
mtcars$`car name` <- factor(mtcars$`car name`, levels = mtcars$`car name`)  # convert to factor to retain sorted order in plot.

ggplot(mtcars, aes(x=`car name`, y=mpg_z, label=mpg_z)) + 
  geom_bar(stat='identity', aes(fill=mpg_type), width=.5)  +
  scale_fill_manual(name="Mileage", 
                labels = c("Above Average", "Below Average"), 
                values = c("above"="#00ba38", "below"="#f8766d")) + 
  labs(subtitle="Normalised mileage from 'mtcars'", 
   title= "Diverging Bars") + 
  coord_flip()

图看起来像这样(x轴上的红色文本是我要添加的内容)...

enter image description here

1 个答案:

答案 0 :(得分:0)

如果设置了annotation_custom,则可以使用clip = off

library(ggplot2)
ggplot(mtcars, aes(x=`car name`, y=mpg_z, label=mpg_z)) + 
  geom_bar(stat='identity', aes(fill=mpg_type), width=.5)  +
  scale_fill_manual(name="Mileage", 
                labels = c("Above Average", "Below Average"), 
                values = c("above"="#00ba38", "below"="#f8766d")) + 
  labs(subtitle="Normalised mileage from 'mtcars'", 
   title= "Diverging Bars") + ylab("") +
  coord_flip(clip = "off") + 
  annotation_custom(textGrob("Below", 
                             gp=gpar(fontsize=13,
                                     col = "red", 
                                     fontface="bold")),
                    xmin=-2, xmax=-2, ymin=-0.5, ymax=-0.5) +
  annotation_custom(textGrob("Above",
                             gp=gpar(fontsize=13,
                                     col = "red",
                                     fontface="bold")),
                    xmin=-2, xmax=-2, ymin=1.5, ymax=1.5) +
      theme(plot.margin = unit(c(1,3,1,1), "lines"))

enter image description here

请记住,设置coord_flip时x和y会切换。