r - 根据值微移 ggplot 文本

标签 r ggplot2

这个问题在这里已经有了答案:





Put labels over negative and positive geom_bar

(1 个回答)


2年前关闭。




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

例如。,

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

最佳答案

我们可以使用,例如,

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

关于r - 根据值微移 ggplot 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54535180/

相关文章:

R绘图: Making two plots closer together on the graph

r - 如何将类别分配给 R 中的列,以便可以对每行对这些类别中的值进行求和?

r - 使用 ggplot2 更改单个图形刻度线的位置

r - ggplot和R : Two variables over time

r - ggplot 中的多行图表而不使用 facet

r - 控制geom_bar的宽度?

r - ggplot 使用分组日期变量(例如 year_month)

r - 如何重命名 R 中 DT 数据表的过滤器中的占位符?

r - 使用 ggplot 绘制月度数据

r - 在 ggplot 中自定义图例