我试图格式化成千的成本和收入以及百万的印象数据,用于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 轴上用逗号表示千位和百万位数,并希望这些数字缩写为 '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
调用中设置的限制,然后仍会引发上述错误。你们有任何想法吗?
unit_format
以了解(b)部分的内容。 - joranlabel = unit_format(unit = "K")
的意思是“标签=label,单位为千”。 - joranunit_format
看起来非常有用;然而我注意到scale_y_continuous(label = unit_format(unit = "m", scale = 1e-6))
将把6000000缩写为6 m
。虽不是什么大事,但在英国使用 **6m
**(无空格)更为普遍。 - Konradunit_format
中使用sep
字段来去除空格。例如,unit_format(unit = "M", scale = 1e-6, sep = "")
。参见 (https://www.rdocumentation.org/packages/scales/versions/0.4.1/topics/unit_format)。 - user3062149