问题
With the help of @Justin on another post, I plotted simulation result with the facet_grid
option in ggplot2. The post with data and answer is here: Use facet_grid option to plot column of dataframe with ggplot2
Here a copy of original sample data with added information about scale_x min and max values for each parameter type :
dat <- read.table(textConnection("P1 P2 P3 P4 R
1 2e-5 1.0 0.6 3 1
2 4e-6 1.5 0.7 1.5 2
3 6e-7 1.2 0.6 2.5 3
4 8e-8 1.45 0.65 3.2 4
"))
scalx <- read.table(textConnection("P XMIN XMAX
1 1 10e-1 10e-10
2 2 0.5 3.0
3 3 0.0 1.5
4 4 2.0 5.0
"))
The code given by @justin for actual example plotting:
library(ggplot2)
library(reshape2)
dat.melt <- melt(dat, id.vars='R')
ggplot(dat.melt, aes(x=0, y=value)) +
geom_boxplot() +
geom_point(aes(colour=factor(R))) +
facet_wrap(~variable, ncol=1, scales='free') +
coord_flip()
But now, my project is to make a little film to show evolution of multiple simulation result, at this time with the help of code given above I obtain great graphic like this.
To make this possible I need to fix the value for each facet, because each parameter can range between fixed extreme values, though what those values are changes from facet to facet.
Do you know if it's possible with facet_grid
because I found recently this issue related to specifying different limits in different facets on the github ggplot2 project repository: https://github.com/hadley/ggplot2/issues/187. Is there another alternative solution to make this possible ?
回答1:
Since you are wanting to expand the scales in each facet (and not restrict/contract them), it is possible. You need to reshape your scalx
into a format similar to your melted dat
:
xlims <- melt(scalx, id.vars="P")
xlims$P <- paste0("P", xlims$P)
names(xlims)[1] <- "variable"
In addition to the melt
, I made the facets have the same format and variable name. This new data frame can then be given to a geom_blank
layer so that it affects the limits of the scales, but does not actually draw anything:
ggplot(dat.melt, aes(x=0, y=value)) +
geom_boxplot() +
geom_point(aes(colour=factor(R))) +
geom_blank(data=xlims) +
facet_wrap(~variable, ncol=1, scales='free') +
coord_flip()
As a side note, your P4
is listed as having a minimum of 2, but actually has a data point at 1.5. This demonstrates that this approach will only expand the scales, not contract them.
来源:https://stackoverflow.com/questions/10869540/overlapping-and-fixing-x-scales-in-facet-scale-free-in-order-to-make-a-film