Reputation: 493
I have a figure with a log scale on the x-axis. Trying to create an inset figure doesn't work, but seems fine if the scale is changed to linear. Is there a way around this, or is it a limitation of ggplot?
This works:
p = qplot(1:10, 1:10)
g = ggplotGrob(qplot(1, 1))
p + annotation_custom(grob = g, xmin = 3, xmax = 6, ymin = 6, ymax = 10)
This doesn't:
p = qplot(1:10, 1:10, log='x')
g = ggplotGrob(qplot(1, 1))
p + annotation_custom(grob = g, xmin = 3, xmax = 6, ymin = 6, ymax = 10)
Upvotes: 4
Views: 3442
Reputation: 493
With a log scale, simply use the exponent rather than the absolute value to specify coordinates. So, in this example, use 0 < x < 1 since the scale runs from 1e0 to 1e1:
p = qplot(1:10, 1:10, log='x')
g = ggplotGrob(qplot(1, 1))
p + annotation_custom(grob = g, xmin = 0.3, xmax = 0.9, ymin = 6, ymax = 10)
Upvotes: 6
Reputation: 8691
With a log scale, x is interpreted as 0 to 1:
p = qplot(1:10, 1:10, log='x')
g = ggplotGrob(qplot(1, 1))
p + annotation_custom(grob = g, xmin = 0.3, xmax = 0.9, ymin = 6, ymax = 10)
so just make it pro-rata
Upvotes: 7
Reputation: 19628
First, I also have problem using ggplot2 to draw inset plot for log scale.
However, I have done some work before using viewport from grid package.
The description of viewport
:
These functions create viewports, which describe rectangular regions on a graphics device and define a number of coordinate systems within those regions.
Basically you can overlap one plot upon another and one upon another...
(1) You can uncomment the command so you can output to a png easily or use dev.copy2**
etc.
(2) x,y,width,height can be specified as unit
object, more info about grid::unit, click here
require(grid)
require(ggplot2)
p = qplot(1:10, 1:10, log="x")
g = qplot(0.1 , 0.1)
vp1 <- viewport(width = 0.3,
height = 0.3,
x = 0.4,
y = 0.7)
vp2 <- viewport(width = 0.3,
height = 0.3,
x = 0.8,
y = 0.3)
#png("text.png")
print(p)
print(g, vp = vp1)
print(g, vp = vp2)
#dev.off()
Upvotes: 3