In the below example i have a simple plot of mean values with standard deviation error bars for both X and Y axis. I would like to control the error bar width so both axis always plot the same size.
Ideally I would like the bar width/height to be the same size as the symbols (i.e. in this case cex = 3) irrelevant of the final plot dimensions. Is there a way to do this?
# Load required packages:
library(ggplot2)
library(plyr)
# Create dataset:
DF <- data.frame(
group = rep(c("a", "b", "c", "d"),each=10),
Ydata = c(seq(1,10,1),seq(5,50,5),seq(20,11,-1),seq(0.3,3,0.3)),
Xdata = c(seq(1,10,1),seq(5,50,5),seq(20,11,-1),seq(0.3,3,0.3)))
# Summarise data:
subDF <- ddply(DF, .(group), summarise,
X = mean(Xdata), Y = mean(Ydata),
X_sd = sd(Xdata, na.rm = T), Y_sd = sd(Ydata))
# Plot data with error bars:
ggplot(subDF, aes(x = X, y = Y)) +
geom_errorbar(aes(x = X,
ymin = (Y-Y_sd),
ymax = (Y+Y_sd)),
width = 1, size = 0.5) +
geom_errorbarh(aes(x = X,
xmin = (X-X_sd),
xmax = (X+X_sd)),
height = 1, size = 0.5) +
geom_point(cex = 3)
Looks fine when plotted at 1:1 ratio (500x500):
but the errorbar width/heigh look different when plotted at 600x200
I'd use a size-variable so you can control all of the 3 plot elements at the same time
geom_size <- 3
# Plot data with error bars:
ggplot(subDF, aes(x = X, y = Y)) +
geom_errorbar(aes(x = X,
ymin = (Y-Y_sd),
ymax = (Y+Y_sd)),
width = 1, size = geom_size) +
geom_errorbarh(aes(x = X,
xmin = (X-X_sd),
xmax = (X+X_sd)),
height = 1, size = geom_size) +
geom_point(cex = geom_size)
This is just building on brettljausn earlier answer. You can control the ratio of your plot with a variable as well. This will only work when you actually save the file with ggsave()
not in any preview. I also used size
to control the size of the point. It scaled nicer with the error bar ends.
plotheight = 100
plotratio = 3
geomsize = 3
plot = ggplot(subDF, aes(x = X, y = Y)) +
geom_errorbar(aes(x = X,
ymin = (Y-Y_sd),
ymax = (Y+Y_sd)),
width = .5 * geomsize / plotratio, size = 0.5) +
geom_errorbarh(aes(x = X,
xmin = (X-X_sd),
xmax = (X+X_sd)),
height = .5 * geomsize, size = 0.5) +
geom_point(size = geomsize)
ggsave(filename = "~/Desktop/plot.png", plot = plot,
width = plotheight * plotratio, height = plotheight, units = "mm")
Change the plotheight
, plotratio
, and geomsize
to whatever you need it to be to look good. You will have to change the filename
in the one but last line to get the file in the folder of your choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With