根据值微调ggplot文本

时间:2019-02-05 13:10:37

标签: 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()

当前,文本显示在负条上方:enter image description here

我只想将这些小节向左微调,对于正数小条向右微调。

示例source

2 个答案:

答案 0 :(得分:3)

我们可能会使用,例如

geom_text(size = 2, nudge_y = -0.1 + 0.2 * (mtcars$mpg_z > 0))

geom_text(size = 2, nudge_y = ifelse(mtcars$mpg_z > 0, 0.1, -0.1))

构造一个nudge_y值的向量。这给出了

enter image description here

答案 1 :(得分:2)

这里,我没有使用nudge_y,而是根据y的符号,手动将固定值添加(或减去)到geom_text中的mpg_z,具体取决于恰当命名的函数sign。与示例不同的唯一一行是geom_text(size=2, aes(y = mpg_z + 0.1 * sign(mpg_z)))

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, aes(y = mpg_z + 0.1 * sign(mpg_z))) +
  labs(subtitle="Normalised mileage from 'mtcars'", 
       title= "Diverging Bars") + 
  coord_flip()

reprex package(v0.2.1)于2019-02-05创建