我使用以下代码构建了条形图:
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()
哪个产生这个:
我希望根据正或负值来调整文本标签,即如果条为正,则将文本标签放在条的右边,如果条为负,则将文本标签放在条的右边栏的左侧。
我试图在情节中添加一个if statement
,但这给了我一个Error: Cannot add ggproto objects together
的错误。如何去做呢?
谢谢
答案 0 :(得分:1)
答案 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()