我试图为ggplot图形的y轴标签格式化成本和收入(以千为单位)以及印象(以百万为单位)数据.
我的绘图从31天前到"昨天",并使用ylim(c(min,max))
选项在该期间的最小值和最大值.仅展示成本示例,
library(ggplot2)
library(TTR)
set.seed(1984)
#make series
start <- as.Date('2016-01-01')
end <- Sys.Date()
days <- as.numeric(end - start)
#make cost and moving averages
cost <- rnorm(days, mean = 45400, sd = 11640)
date <- seq.Date(from = start, to = end - 1, by = 'day')
cost_7 <- SMA(cost, 7)
cost_30 <- SMA(cost, 30)
df <- data.frame(Date = date, Cost = cost, Cost_7 = cost_7, Cost_30 = cost_30)
# set parameters for window
left <- end - 31
right <- end - 1
# plot series
ggplot(df, aes(x = Date, y = Cost))+
geom_line(lwd = 0.5) +
geom_line(aes(y = Cost_7), col = 'red', linetype = 3, lwd = 1) +
geom_line(aes(y = Cost_30), col = 'blue', linetype = 5, lwd = 0.75) +
xlim(c(left, right)) +
ylim(c(min(df$Cost[df$Date > left]), max(df$Cost[df$Date > left]))) +
xlab("")
我想a)用逗号表示y轴上的成千上万,b)用缩写的数字表示,用"K"表示千,或用"MM"表示百万.我意识到b)可能是一项艰巨的任务,但目前a)无法用
ggplot(...) + ... + ylim(c(min, max)) + scale_y_continuous(labels = comma)
因为引发了以下错误:
## Scale for 'y' is already present. Adding another scale for 'y', which
## will replace the existing scale.
我试着把scale_y_continuous(labels = comma)
部分放在geom_line()
层之后(上面会抛出错误),或者放在所有ggplot层的末尾,这会覆盖我在ylim
调用中的限制,然后无论如何都会抛出上面的错误.
有什么 idea 吗?