How to show the part of the errorbar lines which are within the plot margins using `ggplot2`? - r

I have a grid of plots, all with the same y and x-axis scale. The plots represent time in the x-axe and mean values in the y-axe with their standard errors. My problem is that some errorbars are not entirely within the plot margins, and I wonder if there is some way to represent the part of the errorlines that are within the plot margins. Below I give a fake example and code to play with:
df <- data.frame(time=seq(-15,15,1),
mean=c(0.49,0.5,0.53,0.55,0.57,0.59,0.61,0.63,0.65,0.67,0.69,0.71,0.73,0.75,0.77,0.79,0.77,0.75,0.73,0.71,0.69,0.67,0.65,0.63,0.61,0.59,0.57,0.55,0.53,0.51,0.49),
sd=c(0.09,0.087,0.082,0.08,0.023,0.011,0.010,0.009,0.008,0.007,0.006,0.005,0.004,0.003,0.002,0.001,0.002,0.003,0.004,0.005,0.006,0.007,0.008,0.009,0.010,0.011,0.023,0.08,0.084,0.087,0.09))
Plot <- ggplot(df, aes(x=time, y=mean)) +
geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.3) +
geom_point(size=1) +
geom_line () +
theme_bw() +
scale_y_continuous(limits = c(0.49, 0.85), breaks = c(0.5, 0.65,0.8))
Plot

You need to set coord_cartesian limits rather than scale_y_continuous limits:
ggplot(df, aes(x=time, y=mean)) +
geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.3) +
geom_point(size=1) +
geom_line () +
theme_bw() +
scale_y_continuous(breaks = c(0.5, 0.65,0.8)) +
coord_cartesian(ylim = c(0.49, 0.85))

Related

How to flip a geom_area to be under the line when using scale_y_reverse()

I had to flip the axis of my line, but still need the geom_area to be under the curve. However I cannot figure out how to do so.
This is the line of code I tried
ggplot(PalmBeachWell, aes(x=Date, y=Depth.to.Water.Below.Land.Surface.in.ft.)) +
geom_area(position= "identity", fill='lightblue') +
theme_classic() +
geom_line(color="blue") +
scale_y_reverse()
and here is what i got
One option would be to use a geom_ribbon to fill the area above the curve which after applying scale_y_reverse will result in a fill under the curve.
Using some fake example data based on the ggplot2::economics dataset:
library(ggplot2)
PalmBeachWell <- economics[c("date", "psavert")]
names(PalmBeachWell) <- c("Date", "Depth.to.Water.Below.Land.Surface.in.ft.")
ggplot(PalmBeachWell, aes(x = Date, y = Depth.to.Water.Below.Land.Surface.in.ft.)) +
geom_ribbon(aes(ymin = Depth.to.Water.Below.Land.Surface.in.ft., ymax = Inf),
fill = "lightblue"
) +
geom_line(color = "blue") +
scale_y_reverse() +
theme_classic()

R software - Bar graph log Y scale issue

I have made a bar graph and would like it to have a log-scaled y axis. However, when I try to add the code for this, it for some reason inverses most of the bars... Can anyone explain why this may be and how to remedy this?
The code I use is as follows:
Graph1 <- ggplot(Data, aes(x=Temp, y=Mean, fill=Exposure)) +
geom_bar(position=position_dodge(), stat='identity', color="black",) +
xlab("Temperature (°C)") +
ylab("Cd concentration (µg/g)") +
facet_wrap(.~Day, scales="free_y", labeller=labeller(Day=supp.labsDAY), nrow = 1, ncol = 4)+
geom_errorbar( aes(x=Temp, ymin=Mean-SEM, ymax=Mean+SEM), width = 0.2, position=position_dodge(.9))
Graph1+ scale_y_log10()

Remove gaps in a stat_density2d ggplot chart without modifying XY limits

When I run this code:
ggplot() +
stat_density2d(data = Unit_J, aes(x=X, y=Y, fill=..level.., alpha=0.9), lwd= 0.05, bins=50, col="blue", geom="polygon") +
scale_fill_continuous(low="blue",high="darkblue") +
scale_alpha(range=c(0, 0.03), guide="none") +
xlim(-6600,-3800) + ylim(400,2500) +
coord_fixed(expand=FALSE) +
geom_point(data = Unit_J, aes(x=X, y=Y), alpha=0.5, cex=0.4, col="darkblue") +
theme_bw() +
theme(legend.position="none")
I get this plot:
I know that increasing in this case X lims would solve the problem of unclosed lines shown on the left and right.
However, I want to keep these limits unchanged so that those "bugs" don't appear, and simply they must be beyond the limits, somehow hidden without creating those horrible lines.
Is there any possibility?
EDIT (download data here):
In order to ease and reproduce the example, you can download the data here
The trick is to expand the canvas using xlim and ylim so that there is enough room for ggplot to draw complete contours around the data. Then you can use tighter xlim and ylim parameters within the coord_fixed term to show the window you want...
ggplot() +
stat_density2d(data = Unit_J, aes(x=X, y=Y, fill=..level.., alpha=0.9),
lwd= 0.05, bins=50, col="blue", geom="polygon") +
scale_fill_continuous(low="blue",high="darkblue") +
scale_alpha(range=c(0, 0.03), guide="none") +
xlim(-7000,-3500) + ylim(400,2500) + #expanded in x direction
coord_fixed(expand=FALSE,xlim=c(-6600,-3800),ylim=c(400,2500)) + #added parameters
geom_point(data = Unit_J, aes(x=X, y=Y), alpha=0.5, cex=0.4, col="darkblue") +
theme_bw() +
theme(legend.position="none")

Gridlines between discrete values

When using a discrete values ggplot2 provides a gridline at the tick value at the centre of the value
library(reshape2)
ggplot(data=tips, aes(x=time, y=total_bill, fill=sex)) +
geom_bar(stat="identity", position=position_dodge())
How can I set the grid line from the x axis to appear between the discrete values (i.e. between 'Dinner' and 'Lunch')
I have tried to set panel.grid.minor.x however (I think) as it is discrete this does not work ... this is not a minor value for it to plot the girdline on.
ggplot(data=tips, aes(x=time, y=total_bill, fill=sex)) +
geom_bar(stat="identity", position=position_dodge()) +
theme(panel.grid.minor.x = element_line())
You can add a vertical line that will act as a grid line as follows:
geom_vline(xintercept=1.5, colour='white')
You can, of course, alter line width, colour, style, etc. as needed, and add multiple lines in the appropriate locations if you have several groups of bars that need to be separated by grid lines. For example, using some fake data:
set.seed(1)
dat = data.frame(total_bill=rnorm(100,80,10),
sex=rep(c("Male","Female"),50),
time=sample(c("Breakfast","Brunch","Lunch","Afternoon Tea","Dinner"),
100, replace=TRUE))
dat$time = factor(dat$time,
levels=c("Breakfast","Brunch","Lunch","Afternoon Tea","Dinner"),
ordered=TRUE)
ggplot(data=dat, aes(x=time, y=total_bill, fill=sex)) +
geom_bar(stat="identity", position=position_dodge()) +
geom_vline(xintercept=seq(1.5, length(unique(dat$time))-0.5, 1),
lwd=1, colour="black")
Had the same problem. My solution was to make the grid line bigger ..
set.seed(1)
dat = data.frame(total_bill=rnorm(100,80,10),
sex=rep(c("Male","Female"),50),
time=sample(c("Breakfast","Brunch","Lunch","Afternoon Tea","Dinner"),
100, replace=TRUE))
dat$time = factor(dat$time,
levels=c("Breakfast","Brunch","Lunch","Afternoon Tea","Dinner"),
ordered=TRUE)
ggplot(data=dat, aes(x=time, y=total_bill, color=sex)) +
geom_point(stat="identity", position=position_dodge()) +
theme(panel.grid.major.x = element_line(color = "white", size = 20))

can one offset jitter points in ggplot boxplot

In a ggplot boxplot, it is easy to use jitter to add the raw data points with varying degrees of jitter. With zero jitter the following code
dat <- data.frame(group=c('a', 'b', 'c'), values = runif(90))
ggplot(dat, aes(group, values)) +
geom_boxplot(outlier.size = 0) +
geom_jitter(position=position_jitter(width=0), aes(colour=group), alpha=0.7) +
ylim(0, 1) + stat_summary(fun.y=mean, shape=3, col='red', geom='point') +
opts(legend.position = "right") + ylab("values") + xlab("group")
produces the plot below.
Is it possible to use zero jitter but add an offset such that the points are in a line but shifted left by 25% of the box width? I tried geom_point with dodge but this generated a jitter.
If we convert group to numeric and then add an offset, you seem to get your desired output. There is probably a more effective / efficient way, but give this a whirl:
ggplot(dat, aes(group, values)) +
geom_boxplot(outlier.size = 0) +
geom_point(aes(x = as.numeric(group) + .25, colour=group), alpha=0.7) +
ylim(0, 1) + stat_summary(fun.y=mean, shape=3, col='red', geom='point') +
opts(legend.position = "right") + ylab("values") + xlab("group")

Resources