分散条形图-添加文本标签,具体取决于它是负数还是正数

时间:2019-02-18 11:33:06

标签: r ggplot2

我使用以下代码构建了条形图:

regions  <- c("North East", "Northern Ireland", "Wales", "Yorkshire and the Humber", "East Midlands","West Midlands","Scotland",
              "South West", "North West", "London", "East of England", "South East")

First <- c(553,561,600,1192,1718,1777,2091,2296,3147,3590,5105,6975)
Last  <- c(629,647,716,1401,2074,2782,2331,2159,3165,4899,5662,6665)

df  <- data.frame(regions, First, Last)

df$difference = df$Last-df$First 

# Data Prep
df$type <- ifelse(df$difference < 0, "below", "above")  # above / below avg flag
df <- df[order(df$difference), ]  # sort
df$regions <- factor(df$regions, levels = df$regions)  # convert to factor to retain sorted order in plot.

# Diverging Barcharts
ggplot(df, aes(x=`regions`, y=difference, label=difference)) + 
  geom_bar(stat='identity', aes(fill=type), width=.5)  +
  geom_text(aes(label=difference), vjust=0, hjust=1) +
  scale_fill_manual(name="Mileage", 
                    labels = c("Increase", "Decrease"), 
                    values = c("above"="#00ba38", "below"="#f8766d")) + 
coord_flip()

哪个产生这个:

enter image description here

我希望根据正或负值来调整文本标签,即如果条为正,则将文本标签放在条的右边,如果条为负,则将文本标签放在条的右边栏的左侧。

我试图在情节中添加一个if statement,但这给了我一个Error: Cannot add ggproto objects together的错误。如何去做呢?

谢谢

2 个答案:

答案 0 :(得分:1)

这里是您提到的使用mutable的选项

vec

enter image description here

答案 1 :(得分:1)

您需要将hjust参数作为向量传递给geom_text,其中1表示向右调整,0表示向左调整。因此,您可以使用df$difference > 0。像这样:

ggplot(df, aes(x=`regions`, y=difference, label=difference)) + 
  geom_bar(stat='identity', aes(fill=type), width=.5)  +
  geom_text(aes(label=difference), vjust=0, hjust=df$difference > 0) +
  scale_fill_manual(name="Mileage", 
                    labels = c("Increase", "Decrease"), 
                    values = c("above"="#00ba38", "below"="#f8766d")) + 
coord_flip()