如何在条形图中设置面向内的条形标签,并在ggplot2中显示正值和负值?即条形标签应朝向0轴。
df <- data.frame(trt = c("a", "b", "c", "d"),
outcome = c(2.3, 1.9, 0.5, -0.5))
ggplot(df, aes(trt, outcome, label = outcome)) +
geom_bar(stat = "identity",
position = "identity") +
geom_text(vjust = "inward", color = 'red')
vjust = "inward"
不是obviously,因为“向内和向外是相对于图的物理中间,而不是0轴的位置”。
更新:
答案 0 :(得分:2)
您应该能够设置vjust
映射内部的aes
以对每行进行不同的控制,这取决于它是正还是负:
ggplot(df, aes(trt, outcome, label = outcome)) +
geom_bar(stat = "identity",
position = "identity") +
geom_text(aes(vjust = outcome > 0)
, color = 'red')
如果您想更精确地移动标签(而不仅仅是vjust = 0
或vjust = 1
可以从逻辑中获得),您可以使用ifelse
并定义更多位置恰好:
ggplot(df, aes(trt, outcome, label = outcome)) +
geom_bar(stat = "identity",
position = "identity") +
geom_text(aes(vjust = ifelse(outcome > 0
, 1.5, -0.5) )
, color = 'red'
)