所以这是我的代码
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等位于行顶部而不是条形
答案 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"))