“向内”面向条形图中的条形标签,其中负值为ggplot2

时间:2016-09-30 15:52:02

标签: r ggplot2

如何在条形图中设置面向内的条形标签,并在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轴的位置”。

更新:

geom_bar inward

1 个答案:

答案 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')

enter image description here

如果您想更精确地移动标签(而不仅仅是vjust = 0vjust = 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'
            )

enter image description here