如何将行的值添加到ggplot 2中的行顶部

时间:2017-10-11 09:00:03

标签: r

所以这是我的代码

estimated_backlog_value <- 
c(1000,830,1440,1160,420,1230,1200,1520,3330,4710,3190)

names <- c("2006","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016")

avg_sales_per_unit <- c(68,69,89,87,79,80,112,106,106,114,116)

table <- data.frame(names, estimated_backlog_value,avg_sales_per_unit)

p = ggplot(table, aes(names, estimated_backlog_value))+
        geom_bar(fill = ifelse(names != 2016,"green","blue"),
        stat = "identity") +
        xlab("Years") +
        ylab("Backlog value\n($ in millions)") +
        labs(title = "Diverse Railcar Backlog",
            subtitle = "Provides Strong Earnings Visibility") +
        scale_y_continuous(sec.axis = sec_axis(~.*0.032,name = "Average Sales Price/Unit\n($ in thousands)"))


p <- p + geom_line(aes(x = as.numeric(names), y = avg_sales_per_unit/0.032))

p <- p + geom_text(aes(label = estimated_backlog_value),position = position_stack(vjust = 0.5), col = ifelse(names != 2016,"black","red"))

p + geom_text(aes(label=avg_sales_per_unit,vjust=-0.5), col = ifelse(names != 2016,"black","red"))

如何制作与线条对应的数字,因此68,69等位于行顶部而不是条形

由于 the graph

2 个答案:

答案 0 :(得分:0)

您的问题出现是因为geom_text使用条形的x和y坐标而不是线条的x和y坐标。如果您向geom_text添加包含正确坐标的参数数据,您将获得所需位置的文本:

p + geom_text(data = data.frame(x=names,y=avg_sales_per_unit/0.032),aes(x=x,y=y,label=avg_sales_per_unit,vjust=-0.5), 
col = ifelse(names != 2016,"black","red"))

答案 1 :(得分:0)

具体而言,avg_sales_per_unit标签显示在geom_bar上方而不是geom_line上方,因为您将父y=estimated_backlog_value中的aes定义为y位置,例如ggplot(table, aes(names, estimated_backlog_value))

您必须使用geom_text值定义与geom_line相关联的y = avg_sales_per_unit/0.032的y位置值:

p + geom_text(aes(y = avg_sales_per_unit/0.032, label=avg_sales_per_unit,vjust=-0.5), col = ifelse(names != 2016,"black","red"))

编辑回答问题:您可以使用prettyNum格式化数字,包括添加逗号分隔符。您可以在ggplot2中按如下方式实施,以格式化geom_text中的数字标签。

p = p + geom_text(aes(label = prettyNum(estimated_backlog_value, big.mark=",")), position = position_stack(vjust = 0.5), col = ifelse(names != 2016,"black","red"))

p + geom_text(aes(y = avg_sales_per_unit/0.032, label = prettyNum(avg_sales_per_unit, big.mark=","), vjust=-0.5), col = ifelse(names != 2016,"black","red"))

enter image description here