Reputation: 3953
I usually use infinite values in the position aesthetics of ggplot text objects to make labels appear in the corner of the plot regardless of the data scale. I mainly use this when making multi-panel figures which should have letters in each panel to identify each panel in the figure legend. However, this does not seem to work with log scales if I want the label to appear on the left or bottom, since obviously transforming log(-Inf) returns NaN. Is there an easy fix for this? I could do a long workaround but I was hoping there is something easier. Example is below:
notlogdata <- data.frame(x = 1:3,y = 1:3)
ggplot(notlogdata, aes(x = x,y = y)) +
geom_point() +
geom_text(data = data.frame(x = -Inf, y = Inf, l = 'a'), aes(label = l), hjust = -0.5, vjust = 1)
logdata <- data.frame(x = 10^(1:3), y = 10^(1:3))
ggplot(logdata, aes(x = x,y = y)) +
geom_point() +
geom_text(data = data.frame(x = -Inf, y = Inf, l = 'a'), aes(label = l), hjust = -0.5, vjust = 1) +
scale_x_log10() +
scale_y_log10()
First plot with untransformed axes appears fine:
The second plot does not have a label and returns the warning:
Warning messages:
1: In self$trans$transform(x) : NaNs produced
2: Removed 1 rows containing missing values (geom_text).
Upvotes: 1
Views: 1495
Reputation: 145785
You can take a log of Inf
--- log(Inf)
is Inf
. The issue is you can't take a log of a negative like -Inf
. But log(0)
is -Inf
, so if you set x = 0
it will work as expected.
ggplot(logdata, aes(x = x,y = y)) +
geom_point() +
geom_text(
data = data.frame(x = 0, y = Inf, l = 'a'),
aes(label = l), hjust = -0.5, vjust = 1
) +
scale_x_log10() +
scale_y_log10()
Upvotes: 4
Reputation: 77106
annotation_custom(gTree(children=gList(textGrob("a", hjust=0,x=0,vjust=1,y=1))))
Upvotes: 3
Reputation: 3953
It does not appear to be possible to use negative positioning aesthetics, including -Inf
, on a log-transformed axis. Here is a solution using cowplot as suggested by zx8754
library(cowplot)
notlogdata <- data.frame(x = 1:3,y = 1:3)
notlogplot <- ggplot(notlogdata, aes(x = x,y = y)) +
geom_point()
logdata <- data.frame(x = 10^(1:3), y = 10^(1:3))
logplot <- ggplot(logdata, aes(x = x,y = y)) +
geom_point() +
scale_x_log10() +
scale_y_log10()
plot_grid(notlogplot, logplot, labels=c('a','b'), hjust=-8)
This outputs the plot below:
Upvotes: 0