gpt4 book ai didi

r - 发散条形图 - 添加文本标签根据它是负数还是正数进行调整

转载 作者:行者123 更新时间:2023-12-02 00:23:06 25 4
gpt4 key购买 nike

<分区>

我使用以下代码构建了一个发散条形图:

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 语句,但这给了我一个错误:Error: Cannot add ggproto objects together。如何去做这个?

谢谢

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com