带日志的 ggplot 图例

ggplot legend with logs

我正在尝试使用值的对数来填充绘图中的条形图,并使用填充图例来显示原始值。

我想要的图例颜色示例:

library(data.table)
df = data.table(date=Sys.Date()+0:7,
                size=c(100,200,50,300,450,70,50,200),
                objective=c(1,2,2,2,5,2,3,1),
                actuals=c(0.8,2.5,2,2.2,4,1.8,15,0.2))
df[,deviation:=actuals/objective-1]
df[,log_deviation:=log(deviation+1)]

ggplot(df,aes(date,size,fill=log_deviation))+geom_bar(stat="identity")+
  scale_fill_gradient2(high = "tomato", low = "blue",mid = "seagreen1",labels = scales::percent)

我想要的图例值:

ggplot(df,aes(date,size,fill=deviation))+geom_bar(stat="identity")+
  scale_fill_gradient2(high = "tomato", low = "blue",mid = "seagreen1",labels = scales::percent)

有什么优雅的方法吗?谢谢!

您可以在比例尺中定义变换:

ggplot(df,aes(date,size,fill = deviation))+geom_bar(stat="identity")+
  scale_fill_gradient2(high = "tomato", low = "blue",
    mid = "seagreen1",labels = scales::percent, 
    trans = "log1p")

如果您不喜欢默认的分隔符,请在比例内定义 breaks