Creating a composite plot using ggplot in R - r

I am pretty new to R and am trying to create a composite plot using ggplot. I have searched how to do this and have seen I can use the facet function, however, it seems that this is for plotting data which can be split by type e.g. male/female. I have a data frame and I want to plot recovery against concentration, and recovery against equilibrium time on separate plots but as a composite plot. For this I have the following code:
p1 <- ggplot(dat2, aes(x = EqmTime, y = Recovery))
limits <- aes(ymax = Recovery + RecoveryError, ymin=Recovery - RecoveryError)
p1 + geom_point(size = 4) + geom_errorbar(limits, width=4) + geom_smooth(method = "lm", se = FALSE, colour="gray", size=1.5, linetype="dashed") +
labs(x='Equilibrium Time (hrs)', y='Nitrate Recovery (%)') + theme_bw() +
theme(axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())
p2 <- ggplot(dat2, aes(x = StockConc, y = Recovery))
limits <- aes(ymax = Recovery + RecoveryError, ymin=Recovery - RecoveryError)
p2 + geom_point(size = 4) + geom_errorbar(limits, width=0.1) + geom_smooth(method = "lm", se = FALSE, colour="gray", size=1.5, linetype="dashed") +
labs(x='Concentration (g L-1)', y='Nitrate Recovery (%)') + theme_bw() +
theme(axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())
Additionally, I also have a problem that I cannot get the '-1' in the x axis label of plot 2 as a superscript, and am having trouble setting axis limits. When I set, for example, xlim=20-180, the axis doesn't start and finish at these, but makes these the major tick marks.
I would greatly appreciate any help with this! I know some of these issues have been addressed in other posts but I cannot seem to use this advise to sort the issue here.

From your question, I understand that you want to plot both the ggplots in single plot window. You can do this using gridextra package as:
library(gridExtra)
grid.arrange(p1, p2, nrow=2)

Related

Can you get the axis of the marginal densities to line up with the axis of the scatter plot

Hi I have the plot below and the marginal density plots are slightly off. They do not line up to the x and y axis of the scatter plot so interpretation can be a bit misleading.
I can sort of play with these lines of code to try and get the margins to align for rthe marginal plots but it is very manual and frustrating.
theme0(plot.margin = unit(c(1,0,0,2.2),"lines"))
theme0(plot.margin = unit(c(0,1,1.2,0),"lines"))
Is there a way to automatically find the right margins to pass to theme0(plot.margin = unit(c(0,1,1.2,0),"lines") so that no manual work needs to be done to line up the margins? Thank you.
library(ggplot2)
library(gridExtra)
set.seed(42)
DF <- data.frame(x=rnorm(100,mean=c(1,5)),y=rlnorm(100,meanlog=c(8,6)),group=1:2)
DF
## Scatter plot
p1 <- ggplot(DF,aes(x=x,y=y)) + geom_point() +
scale_x_continuous(expand=c(0.02,0)) +
scale_y_continuous(expand=c(0.02,0)) +
theme_bw() +
theme(legend.position="none",plot.margin=unit(c(0,0,0,0),"points")) # ggplot(DF,aes(x=x,y=y,colour=factor(group))) color the gorup
theme0 <- function(...) theme( legend.position = "none",
panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.margin = unit(0,"null"),
axis.ticks = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.ticks.length = unit(0,"null"),
axis.ticks.margin = unit(0,"null"),
panel.border=element_rect(color=NA),...)
### DENSITY OF X
p2 <- ggplot(DF,aes(x=x, fill="blue")) +
geom_density(alpha=0.5) +
scale_x_continuous(breaks=NULL,expand=c(0.02,0)) +
scale_y_continuous(breaks=NULL,expand=c(0.02,0)) +
theme_bw() +
theme0(plot.margin = unit(c(1,0,0,2.2),"lines")) # to color group ggplot(DF,aes(x=x,colour=factor(group),fill=factor(group)))
### DENSITY OF Y
p3 <- ggplot(DF,aes(x=y, fill = "red")) +
geom_density(alpha=0.5) +
coord_flip() +
scale_x_continuous(labels = NULL,breaks=NULL,expand=c(0.02,0)) +
scale_y_continuous(labels = NULL,breaks=NULL,expand=c(0.02,0)) +
theme_bw() +
theme0(plot.margin = unit(c(0,1,1.2,0),"lines")) # color group ggplot(DF,aes(x=y,colour=factor(group),fill=factor(group)))
grid.arrange(arrangeGrob(p2,ncol=2,widths=c(3,1)),
arrangeGrob(p1,p3,ncol=2,widths=c(3,1)),
heights=c(1,3))

ggplot classic theme missing axes [duplicate]

I am trying to draw this following graph using ggplot2 package, but somehow the axis won't show up. the ticks are there, just not the axis line. I have used the theme(axis.line=element_line()) function, but it wouldn't work.
Here is my code:
library(ggplot2)
ggplot(data = soepl_randsub, aes(x = year, y =satisf_org, group = id)) +
geom_point() + geom_line() +ylab("Current Life Satisfaction") +theme_bw() +
theme(plot.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank() ) +
theme(panel.border= element_blank()) +
theme(axis.line = element_line(color="black", size = "2"))
I am not sure what went wrong. Here is the chart.
The bug was fixed in ggplot2 v2.2.0 There is no longer a need to specify axis lines separately.
I think this is a bug in ggplot2 v2.1.0. (See this bug report and this one.) A workaround is to set the x-axis and y-axis lines separately.
library(ggplot2)
ggplot(data = mpg, aes(x = hwy, y = displ)) +
geom_point() +
theme_bw() +
theme(plot.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank() )+
theme(panel.border= element_blank())+
theme(axis.line.x = element_line(color="black", size = 2),
axis.line.y = element_line(color="black", size = 2))
You don't need to specify axis-size for X and Y separately. When you are specifying size="2", R is considering value 2 as non-numeric argument. Hence, axis-line parameter is defaulted to 0 size. Use this line of code:
ggplot(data = mpg, aes(x = hwy, y = displ)) + geom_point() +xlab("Date")+ylab("Value of Home")+theme_bw() +theme(plot.background = element_blank(),panel.grid.major = element_blank(),panel.grid.minor = element_blank()) + theme(panel.border= element_blank()) +
theme(axis.line = element_line(color="black", size = 2))
axis_line inherits from line in R, hence specifying size is mandatory for non-default values.

Scatterplots in R ggplot2 package: moving axes and changing font label sizes

I'm trying to replicate the following chart using ggplot2
The one change I'd like to make from that chart though is to give a colour to each point and its label. Here's what I've tried so far:
library(ggplot2)
library(directlabels)
Z <- c("Label1", "Label2", "Label3", "Label4", "Label5", "Label6", "Label7",
"Label8", "Label9", "Label10", "Label11", "Label12", "Label13", "Label14",
"Label15", "Label16", "Label17", "Label18", "Label19", "Label20", "Label21",
"Label22", "Label23", "Label24")
X <- c(10.32582421, 9.772686421, -13.99202201, 3.803952545, 7.775395482,
-11.82234956, -24.27906403, -6.864457678, -24.62853773, 15.3562638,
-6.476057462, 9.576414602, -5.504090215, 29.74512913, 9.046116821,
15.79954557, -39.61679645, -0.90307239, 21.12503086, 15.30221473,
13.40781808, -6.803226537, -4.045907666, -0.134057007)
Y <- c(0.037608141, 0.010581738, 0.117730985, 0.022347258, 0.069347278,
0.026699666, 0.028739498, 0.040611306, 0.036626248, 0.034854158,
0.039310836, 0.03122964, 0.009422296, 0.021935924, 0.050006846,
0.036285691, 0.016796701, 0.057764277, 0.028421772, 0.042726693,
0.037513217, 0.058422072, 0.066859355, 0.078158403)
mychart <- data.frame(Z, X, Y)
q <- ggplot(mychart, aes(X, Y)) + geom_point(aes(colour = Z)) + theme_bw()
direct.label(q)
And I get the following result:
There are three things I'm having trouble figure out:
I'd like to remove the grey quadrant lines.
I'd like to move the axes so that they are centered in the chart, with plots distributed across the 4 quadrants.
I'd like to reduce the label font sizes - I suspect that's why some of them don't end up close to their points.
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"))
Use +xlim(min,max) and +ylim(min,max) to set the axis limits for your plot. Then you can use +geom_hline(y=yvalue) and +geom_vline(x=xvalue) to add the horizontal and vertical lines to your plot to designate the four quadrants.
Instead of using +direct.label(q), use +geom_text(aes(label=q,size=sizevalue),where 'sizevalue' is a numeric value that determines the size of the labels (so you can experiment with this).
EDIT: Try this code, which should fix your point labels. (I don't know of a way to move the axis labels up to the lines you drew in, nor a native way to simply move the original axes into the center of your plot. Sorry!):
ggplot(mychart, aes(X, Y)) +
geom_point(aes(colour = Z)) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "black")) +
xlim(-40,40) +
ylim(0,0.12) +
geom_hline(y=0.04) +
geom_vline(y=0) +
geom_text(aes(x=X,y=Y+0.003,label=Z,color=Z)) +
theme(legend.position="none")
EDIT 2: Jitter in geom_text
ggplot(mychart, aes(X, Y, colour=Z)) +
geom_point() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "black")) +
geom_text(aes(label=Z),
position = position_jitter(width=2, height=0.005)) +
xlim(-40,40) +
ylim(0,0.12) +
geom_hline(y=0.04) +
geom_vline(y=0) +
theme(legend.position="none")

Using geom_path from ggplot library

I have 12 variables, M1, M2, ..., M12, for which I compute a certain statistic x.
df = data.frame(model = factor(paste("M", 1:28, sep = ""), levels=paste("M", 1:28, sep = "")), x = runif(28, 1, 1.05))
levels = seq(0.8, 1.2, 0.05)
I would like to plot this data as follows:
Each circle (contour) represents the a level of that statistic "x". The three blue lines simply represent three different scenarios.
The dataframe included in this example represents one scenario. The blue line would simply join the values of all the models M1 to M28 for that specific scenario.
I tried the following:
ggplot(data=df, aes(x=model, y=x, group=1)) +
geom_line() + coord_polar() +
scale_y_continuous(limits=range(levels), breaks=levels, labels=levels) +
theme(axis.text.y = element_blank(), axis.ticks = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank())
However, I get a disconnected path (between M28 and M1)
Then, I replicated the first row and placed it at the bottom of the dataframe (see below), and then used geom_path() instead of geom_line(), but I didn't get the result I was looking for:
## Replicating the first row (model1) and placing it at end of dataframe
df = rbind(df, df[1,])
## using geom_path()
ggplot(data=df, aes(x=model, y=lg, group=1)) +
geom_path() + coord_polar() +
scale_y_continuous(limits=range(levels), breaks=levels, labels=levels) +
theme(axis.text.y = element_blank(), axis.ticks = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank())
Could any please help me achieve the result that I am looking for? Any help would be appreciated. Thanks!
You have to use geom_polygon for closed paths:
library(ggplot2)
ggplot(data=df, aes(x=model, y=x, group=1)) +
geom_polygon(fill = NA, colour = "black") +
coord_polar() +
scale_y_continuous(limits=range(levels), breaks=levels, labels=levels) +
theme(axis.text.y = element_blank(), axis.ticks = element_blank(),
axis.title.x = element_blank(), axis.title.y = element_blank())

scatterplot with alpha transparent histograms in R

How can scatter plots with alpha transparent, scale-less histograms can be made in R, like this figure?
looks like it's not made in ggplot2.
does anyone know what command is used?
library(ggplot2)
library(gridExtra)
set.seed(42)
DF <- data.frame(x=rnorm(100,mean=c(1,5)),y=rlnorm(100,meanlog=c(8,6)),group=1:2)
p1 <- ggplot(DF,aes(x=x,y=y,colour=factor(group))) + geom_point() +
scale_x_continuous(expand=c(0.02,0)) +
scale_y_continuous(expand=c(0.02,0)) +
theme_bw() +
theme(legend.position="none",plot.margin=unit(c(0,0,0,0),"points"))
theme0 <- function(...) theme( legend.position = "none",
panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.margin = unit(0,"null"),
axis.ticks = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.ticks.length = unit(0,"null"),
axis.ticks.margin = unit(0,"null"),
panel.border=element_rect(color=NA),...)
p2 <- ggplot(DF,aes(x=x,colour=factor(group),fill=factor(group))) +
geom_density(alpha=0.5) +
scale_x_continuous(breaks=NULL,expand=c(0.02,0)) +
scale_y_continuous(breaks=NULL,expand=c(0.02,0)) +
theme_bw() +
theme0(plot.margin = unit(c(1,0,0,2.2),"lines"))
p3 <- ggplot(DF,aes(x=y,colour=factor(group),fill=factor(group))) +
geom_density(alpha=0.5) +
coord_flip() +
scale_x_continuous(labels = NULL,breaks=NULL,expand=c(0.02,0)) +
scale_y_continuous(labels = NULL,breaks=NULL,expand=c(0.02,0)) +
theme_bw() +
theme0(plot.margin = unit(c(0,1,1.2,0),"lines"))
grid.arrange(arrangeGrob(p2,ncol=2,widths=c(3,1)),
arrangeGrob(p1,p3,ncol=2,widths=c(3,1)),
heights=c(1,3))
Edit:
I couldn't find out what causes the space below the densities geoms. You can fiddle with the plot margins to avoid it, but I don't really like that.
p2 <- ggplot(DF,aes(x=x,colour=factor(group),fill=factor(group))) +
geom_density(alpha=0.5) +
scale_x_continuous(breaks=NULL,expand=c(0.02,0)) +
scale_y_continuous(breaks=NULL,expand=c(0.00,0)) +
theme_bw() +
theme0(plot.margin = unit(c(1,0,-0.48,2.2),"lines"))
p3 <- ggplot(DF,aes(x=y,colour=factor(group),fill=factor(group))) +
geom_density(alpha=0.5) +
coord_flip() +
scale_x_continuous(labels = NULL,breaks=NULL,expand=c(0.02,0)) +
scale_y_continuous(labels = NULL,breaks=NULL,expand=c(0.00,0)) +
theme_bw() +
theme0(plot.margin = unit(c(0,1,1.2,-0.48),"lines"))
I have no idea whether there is a package that does that directly, but I'm sure this can be done in R. Transparency is easy: you add another two digits to the RGB specification of a color for a given transparency:
#FF0000 # red
#FF0000FF # full opacity
#FF000000 # full transparency
Combining different plots is also easy using the layout function. As for the vertical density plot, it is just the same as the horizontal plot with x and y switched. The example given here can easily be expanded to include colors, smaller margins etc. I can try to come up with a more elaborate example if this description is not sufficient.

Resources