根据值微调ggplot文本 [英] Nudge ggplot text based on value
本文介绍了根据值微调ggplot文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何根据值微调文本:
例如,
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()
当前,文本显示在负条上方:
Currently, text shows on top of negative bars:
我只想将这些小节向左微移,对于正数小条向右微移.
I'd like to nudge it to the left only for these bars, to the right for positive bars.
示例源
推荐答案
我们可能会使用,例如,
We may use, e.g.,
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
值的向量.这给出了
to construct a vector of nudge_y
values. This gives
这篇关于根据值微调ggplot文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文