根据值微移 ggplot 文本

dze*_*zer 3 r ggplot2

我将如何根据值轻推文本:

例如,

library(ggplot2)
theme_set(theme_bw())  

# Data Prep
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.

# Diverging Barcharts
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")) + 
  geom_text(size=2, nudge_y = 0.1) +
  labs(subtitle="Normalised mileage from 'mtcars'", 
       title= "Diverging Bars") + 
  coord_flip()
Run Code Online (Sandbox Code Playgroud)

目前,文本显示在负条的顶部: 在此处输入图片说明

我只想将它向左轻推这些条,向右轻推这些条。

示例源

Jul*_*ora 5

我们可以使用,例如,

geom_text(size = 2, nudge_y = -0.1 + 0.2 * (mtcars$mpg_z > 0))
Run Code Online (Sandbox Code Playgroud)

或者

geom_text(size = 2, nudge_y = ifelse(mtcars$mpg_z > 0, 0.1, -0.1))
Run Code Online (Sandbox Code Playgroud)

构造一个nudge_y值向量。这给

在此处输入图片说明