Spreading out facetted plots (R) - r

Is there a way to spread facetted plots apart in ggplot2? As you can see in the picture (the bottom section of my plot), the x-axes are overlapping a bit at the ends of each plot, obscuring the years. I'd like to move them apart. No matter how much I increase the width when exporting, the values still overlap.
My code, if relevant:
ggplot(filter(TotalsRegion, Source!="Total"), aes(x=Date, y=SourceSum, col=Source)) +
geom_line(size=1) +
facet_grid(.~Region)

Since you did not provide a reproducible example, we'll have to make one for you.
library(ggplot2)
library(grid)
data(mpg)
mpg$displ <- mpg$displ + 2000
p <- ggplot(mpg, aes(displ, cty))
p <- p + geom_point()
p <- p + facet_grid(. ~ cyl)
p
p <- p + theme(panel.margin.x=unit(20, "pt"))
p
This does not suffer from the overlap (can't do all the work for you) but hopefully it's clear what the panel margin settings do.

Related

Adding labels to each individual plot with facet_grid

I am attempting to add labels (capital letters) to each plot in the following facet_grid:
p <- ggplot(mpg, aes(displ, cty)) + geom_point()
p + facet_grid(drv ~ cyl)
This outputs:
What I would like to have is this:
The major issues I am having is 1) My Y axis is scaled freely, so inputting specific coordinates for each isn't working. 2) I am not sure what keywords I should be searching here, I am sure there is a way to do this in facet_grid but I am unable to find it.
How about this? Fixing the position of label as the upper-left corner of each plot panel:
p + facet_grid(drv ~ cyl)+ annotate('text', label = LETTERS[1:12], x=min(mpg$displ), y=max(mpg$cty))
You can replace label =c('aaa','bb','fff'....), anything you like, but has to be the same number of your facet plots.
You can also fine-tune the position of the label proportional to both axis by using:
x=mean(mpg$displ)*0.6, y=max(mpg$cty)*0.97

R: fct_reorder() and making a grid of plots - not compatible?

I'm using fct_reorder() to order the levels of my factors in ggplot. That works fine for individual plots. But when I use plot_grid() from cowplot, there is some kind of problem. For contrast, to the left, I've used a plot that has fixed factor levels, not using fct_reorder.
Edited:
Here is the actual code I'm using:
#make the base
myplot <-filter(summary_by_intensity_reshaped, str_detect(feature, "binary"), Frequency == "2Hz") %>%
ggplot(., aes(fct_reorder(feature, mean),mean,fill=Intensity, ymax=mean+sem, ymin=mean-sem))
#add the layers
myplot + geom_bar(stat="identity", position=position_dodge()) +
geom_errorbar(aes(width=0.2),position=position_dodge(0.9)) +
labs(x="Behavior",y="Percent of Trials (%)") +
scale_x_discrete(breaks=c("binary_flutter", "binary_hold", "binary_lift", "binary_jump","binary_rear", "binary_lick", "binary_guard", "binary_vocalize"), labels=c("Flutter", "Holding", "Lifting", "Jumping", "Rearing", "Licking", "Guarding", "Vocalizing"))+
facet_grid(~Frequency)+
theme(axis.text.x=element_text(angle=-90))
And the output looks like this:
The problem arises when I try to use 'myplot' in plot_grid(). That's when it renders oddly as in the example below.
I suspect you're using fct_reorder() incorrectly. plot_grid() just takes whatever plot you make and puts it into a grid.
library(ggplot2)
library(cowplot)
library(forcats)
p1 <- ggplot(mpg, aes(class, displ, color = factor(cyl))) + geom_point()
p2 <- ggplot(mpg, aes(fct_reorder(class, displ, mean), displ, color = factor(cyl))) +
geom_point()
plot_grid(p1, p2)
From your x axis title in the plot on the right, it looks to me like you forgot to provide fct_reorder() with the vector to which it should apply the function.

how can i show the corresonding number in the picture from legend in ggplot2

I used the code ggplot(product_info,aes(x=lat,y=lon,colour=factor(location)))+geom_point()
,picture like this
I want to the number from legend show in the picture with these colourful point together.
You can show the text for the corresponding factor using geom_text(). Here's an example with the diamonds data-set:
ggplot(diamonds, aes(x=price, y=carat, colour=factor(cut), label=factor(cut))) +
geom_point() +
geom_text()
Alternatively, you could consider ggplotly which would provide an easier way of viewing the data
library(plotly)
p <- ggplot(diamonds, aes(x=price, y=carat, colour=factor(cut)))
+ geom_point()
ggplotly(p)

Consistent plotting panel width/height when using gridExtra

I'm trying to construct a 5 x 6 matrix of plots in R using ggplot2 and gridExtra. For simplicity, I can show my issue with a 2 x 2 matrix and some fake data.
#Load libraries
library(ggplot2); library(gridExtra)
#Data
data = rbind(data.frame(x=rnorm(100,0,1),ALP='A',NUM=1),data.frame(x=rnorm(100,20000,1000),ALP='A',NUM=2),data.frame(x=rnorm(100,100,10),ALP='B',NUM=1),data.frame(x=rnorm(5000,1000),ALP='B',NUM=2))
#Ggplot2 facet_grid
ggplot(data,aes(x=x,y=..scaled..,fill='red')) + geom_density() + facet_grid(ALP~NUM,scales='free') + guides(fill=FALSE)
The result doesn't look good, as the x-scale is so different across the faceting labels. I tried to do it manually with gridExtra.
#Assemble grobs
plt1 = ggplot(subset(data,ALP=='A'&NUM==1),aes(x=x,y=..scaled..,fill=ALP)) + geom_density() + facet_grid(.~NUM,scales='free') + guides(fill=FALSE) + theme(axis.title.x=element_blank(),axis.title.y=element_blank())
plt2 = ggplot(subset(data,ALP=='A'&NUM==2),aes(x=x,y=..scaled..,fill=ALP)) + geom_density() + facet_grid(ALP~NUM,scales='free') + guides(fill=FALSE) + theme(axis.text.y=element_blank(),axis.ticks.y=element_blank(),axis.title.y=element_blank(),axis.title.x=element_blank())
plt3 = ggplot(subset(data,ALP=='B'&NUM==1),aes(x=x,y=..scaled..,fill=ALP)) + geom_density() + guides(fill=FALSE) + theme(axis.title.x=element_blank(),axis.title.y=element_blank())
plt4 = ggplot(subset(data,ALP=='B'&NUM==2),aes(x=x,y=..scaled..,fill=ALP)) + geom_density() + facet_grid(ALP~.,scales='free') + guides(fill=FALSE) + theme(axis.text.y=element_blank(),axis.ticks.y=element_blank(),axis.title.y=element_blank(),axis.title.x=element_blank())
#Plot it out
grid.arrange(plt1,plt2,plt3,plt4,nrow=2,ncol=2,left=textGrob("scaled",rot=90,vjust=1),bottom=textGrob("x"))
I'm almost there, unfortunately the plotting panel (x,y) in the upper, right-hand corner is smaller than all the rest. Similarly, the plotting panel (x,y) in the lower, left-hand corner is bigger than all the rest. I would like all of the plotting panels (x,y) to be the same height/width. I found some code using gtable, but it only seems to work consistently when the grobs don't have facet labels. The effect is even more exaggerated when the number of rows/columns increases.
as an alternative to facetting, you could work with gtable,
plt <- lapply(list(plt1,plt2, plt3,plt4), ggplotGrob)
left <- rbind(plt[[1]], plt[[3]])
right <- rbind(plt[[2]], plt[[4]])
all <- cbind(left, right)
grid.newpage()
grid.draw(all)
the panel sizes should all be equal (1null) with this layout.

how do I get rid of random background grid from arrangeGrob

I need to wrap several plots in a grid, often an uneven number, so there'll often be an "empty spot".
I need to use arrangeGrob() -- not grid.arrange() -- because I want to save the plot for later, not plot() it right away.
This works fine, but oddly, arrangeGrob() leaves some weird background in the empty spots.
Like so:
library(ggplot2)
p1 <- ggplot(mtcars, aes(x=factor(cyl), y=mpg)) + geom_boxplot()
p2 <- ggplot(mtcars, aes(x=factor(cyl), y=wt)) + geom_boxplot()
p3 <- ggplot(mtcars, aes(x =factor(cyl), y=disp)) + geom_boxplot()
library(gridExtra)
y <- arrangeGrob(p1, p2, p3, ncol = 2)
plot(y)
yields a plot with some weird gray stuff in the bottom right corner:
Compare this to grid.arrange():
grid.arrange(p1, p2, p3, ncol = 2)
yields a pretty plot with no grey weirdness:
Where does this gray stuff in the bottom right corner come from? And how do I get rid of it?
Notice that I cannot avoid the empty spots by changing ncol; I sometimes have an uneven number of plots, so there'll always be empty spots.
I'm ok with empty spots, I just like them to be clean.
(In isolation, that last sentence sounds pretty OCD-ish.
UPDATE
The package author (?) answered below: I should have used grid.draw(y).
A similar problem remains (maybe the same root cause?): if you plot some object before, the "empty spot" remains occupied by that past plot.
Weird.
Like so:
plot(p1)
grid.draw(y)
yields:
arrangeGrob() now returns a gtable, which you should draw with grid.draw(), not plot().
grid.draw(y)
yields
To get rid of artefacts from past plots (as per above update) use grid.newpage().
Remove the nrow argument. Like so:
library(ggplot2)
p1 <- ggplot(mtcars, aes(x=factor(cyl), y=mpg)) + geom_boxplot()
p2 <- ggplot(mtcars, aes(x=factor(cyl), y=wt)) + geom_boxplot()
library(gridExtra)
y <- arrangeGrob(p1, p2, ncol = 2)
plot(y)

Resources