geom_errorbar() overlap and positioning issues - r

I am having trouble with geom_errorbars particularly in utilizing position_dodge() effectively in this script.
library(ggplot2)
library(plyr)
Dose <- rep(c(3,10,30,100), each = 6)
Visit <- rep(c(1,28), each = 3, times = 4)
Animal <- rep(1:3, times = 8)
Estimate <- runif(24)
Dose <- factor(Dose)
Visit <- factor(Visit)
df <- data.frame(Animal, Dose, Visit, Estimate)
e <- ddply(df, .(Dose, Visit), summarise, mean = mean(Estimate), sd = sd(Estimate), n = length(Estimate))
e$se = e$sd/sqrt(e$n)
trace.out <- ggplot(data = e, aes(x = Visit, y = mean, colour = Dose))
trace.out <- trace.out +
geom_point(data = e, aes(y = mean), size = 3, postion = position_dodge(width = 0.2)) +
geom_line(data = e, aes(y = mean, group = Dose), position = position_dodge(width = 0.2)) +
geom_errorbar(aes(ymin= mean - se, ymax = mean + se), postion = position_dodge(0.2), colour='black', width= 0.3) +
labs(y = 'Estimate') +
theme_bw()
print(trace.out)
The output for me looks like:
I would like for the points, lines and error bars to line up and to have the errorbars not overlap. Is there some way to do that? Additionally I get an error of:
ymax not defined: adjusting position using y instead
Would this have anything to do with it? Thanks in Advance!

Maybe facets are an option:
trace.out <- ggplot(data = e, aes(x = Visit, y = mean, colour = Dose, ymin= mean - se, ymax = mean + se, group = Dose))
trace.out <- trace.out +
geom_point(size = 3, postion = position_dodge(width = 0.2)) +
geom_line(position = position_dodge(width = 0.2), ) +
geom_errorbar(postion = position_dodge(0.2), colour='black', width= 0.3) +
labs(y = 'Estimate') +
theme_bw()
print(trace.out + facet_grid(~Dose) )

Related

How to adjust the label distance with error bar?

Normally, vjsust = adjust the label distanace with the max y value, which is not beautiful when the sd is different, is it possible to adjust it with an equal relative distance with upper error bar?
In the following example, the a and b should be move down and c up, how to plot it?
df <- data.frame(dose=c("D0.5", "D1", "D2"),
len=c(4.2, 10, 29.5), sd = c(0.2, 2, 5),
label = c('a', 'b', 'c'))
ggplot(df, aes(x = dose, y = len)) +
geom_errorbar(aes(ymin = len, ymax = len + sd), width=.1, position=position_dodge(.6)) +
geom_bar(position = position_dodge(), stat="identity", width=.4)+
geom_text(aes(label = label, angle = 0),vjust = -2.5)
Use the y parameter in the geom_text aestethics to set up the position of the labels according to the error bars:
ggplot(df, aes(x = dose, y = len)) +
geom_errorbar(aes(ymin = len, ymax = len + sd), width=.1, position=position_dodge(.6)) +
geom_bar(position = position_dodge(), stat="identity", width=.4)+
geom_text(aes(y = len + sd, label = label, angle = 0),vjust = -2.5) +
ylim(0, 40)

Adding a dotted line between two categorical points in R

I'm new to R and I've scripted the interaction plot below, for which I want two dotted lines connecting both "coral" and both "darkgoldenrod2" points respectively:
df <- tibble::tribble(~Proportion, ~Lower,~Upper, ~Area,~Time,
invlogit(-0.033886), invlogit(-0.517223067), invlogit(0.449451067), "SNP", "Day",
(invlogit(-0.9231219)+invlogit(-0.3786)), 0.5727 ,0.8087, "SNP", "Night",
invlogit(-0.9231219), invlogit(-1.406458967), invlogit(-0.439784833),"LGCA", "Day",
invlogit(-0.1604356), invlogit(-0.643772667) ,invlogit(0.322901467), "LGCA","Night")
df
dfnew <- df %>%
mutate(ymin = Proportion - Lower,
ymax = Proportion + Upper)
p <- ggplot(data = dfnew, aes(x = Time, y = Proportion, color=Area)) +
geom_point(size = 6, stroke = 0, shape = 16,
position = position_dodge(width = 0.1))+
geom_errorbar(aes(y=Proportion, ymin = Lower, ymax = Upper),width=0.1,size=1,
position = position_dodge(width = 0.1)) +
theme(axis.text=element_text(size=15),
axis.title=element_text(size=20)) +
scale_color_manual(values = c("SNP" = "coral",
"LGCA" = "darkgoldenrod2"))
p
Reading other posts here on SO, I've used the command line: +geom_line(aes(group = 1),size=2)
This however isn't producing the desired plot as you can see below:
Any help with this is truly appreciated!
You should add group=Area to your ggplot mapping and then you just need to call geom_line. You also don't need y=Position in geom_errorbar.
p <- ggplot(data = dfnew, aes(x = Time, y = Proportion, color=Area, group=Area)) +
geom_point(size = 6, stroke = 0, shape = 16,
position = position_dodge(width = 0.1))+
geom_errorbar(aes(ymin = Lower, ymax = Upper), width=0.1, size=1,
position = position_dodge(width = 0.1)) +
theme(axis.text=element_text(size=15),
axis.title=element_text(size=20)) +
scale_color_manual(values = c("SNP" = "coral",
"LGCA" = "darkgoldenrod2")) +
geom_line(size=2)
p

ggplot2:: Facetting plot with the same reference plot in all panels

I would like to facet a plot, but with a reference plot in each panel. Let me try to show with pictures what I want to achieve: My example data_frame:
require(dplyr)
df <- data_frame( id = c(rep('ctr',40), rep('pat',80)),
class = c(rep('ctr',40), rep(c('a','b'), each = 40)),
rank = rep (1:20,6),
mean = c(rep(seq(3,-3, length.out = 20),2),
rep(seq(1,-4, length.out = 20),2),
rep(seq(-2,-8, length.out = 20),2)),
sd = rep(seq(1.2,0.8, length.out = 20), times = 6),
exam = rep(c('blue','red'), each = 20, times = 3))
My plot:
# first, create reference plot of the 'controls'
require(ggplot2)
p_ctr <- ggplot() +
geom_line(data = filter(df, id == 'ctr'),
aes(x=rank, y=mean, color=exam), linetype=1) +
geom_ribbon(data = filter(df, id == 'ctr'),
aes(x = rank, ymax = mean+sd, ymin = mean-sd,
fill = exam), alpha = .1) +
scale_colour_manual(values = c("#00b6eb","#eb0041")) +
scale_fill_manual(values = c("#00b6eb","#eb0041"))
# then, overlay with plot of 'patients'
p_ctr + geom_line(data = filter(df, id == 'pat'),
aes(x=rank, y=mean, linetype = class)) +
geom_ribbon(data = filter(df, id == 'pat'),
aes(x = rank, ymax = mean+sd, ymin = mean-sd,
group = class),
alpha = .1) +
facet_wrap(~exam)
That is halfway there:
Ideally, however, I would like to plot the different "classes" in separate panels, but with the control plot as a reference in each panel:
Expected result:
I have tried different combinations of facetting, without good result. I guess, there must be a simple solution?
Maybe like so.
library(dplyr)
library(ggplot2)
df1 <- filter(df, id == 'ctr')
df2 <- filter(df, id == 'pat')
df2 <- dplyr::rename(df2, class_2 = class)
p_ctr <- ggplot() +
geom_line(data = df1, aes(x=rank, y=mean, color=exam)) +
geom_ribbon(data = df1,
aes(x = rank, ymax = mean+sd, ymin = mean-sd, fill = exam),
alpha = .1) +
scale_colour_manual(values = c("#00b6eb","#eb0041")) +
scale_fill_manual(values = c("#00b6eb","#eb0041")) +
geom_line(data = df2,
aes(x=rank, y=mean)) +
geom_ribbon(data = df2,
aes(x = rank, ymax = mean+sd, ymin = mean-sd),
alpha = .1) +
facet_grid(class_2 ~ exam)
p_ctr
Using facet_wrap gives me the following error:
error in gList(list(x = 0.5, y = 0.5, width = 1, height = 1, just = "centre", :
only 'grobs' allowed in "gList"
You probably came across this plot while looking for the solution.
p_ctr + geom_line(data = filter(df, id == 'pat'),
aes(x=rank, y=mean)) +
geom_ribbon(data = filter(df, id == 'pat'),
aes(x = rank, ymax = mean+sd, ymin = mean-sd),
alpha = .1) +
# facet_wrap(~exam) +
facet_grid(class ~ exam)
This is basically your reference plot and its overlay, without the linetype and group arguments. Additionally I faceted by class ~ exam. From this plot you see that 'the problem' is that class contains three unique elements: a, b and ctr. That's why I renamed the variable class in df2 to be class_2 which has only two unique elements: a and b. Faceting by class_2 ~ exam then gives the desired output.
I hope this helps.

how to put mean lines in ggplot?

I am try to do a plot whith means lines by group (in ggplot), and i have my code like this
ggplot(gama, aes(x = distancia, y= glipidoscmtejido, colour= estado)) +
geom_point(position=position_dodge(.5), alpha= 1, size=3) +
geom_crossbar(data=gama,aes(x=distancia,ymin=mean(glipidoscmtejido),
ymax=mean(glipidoscmtejido),y=mean(glipidoscmtejido),colour=estado), width = 0.5)
and I get this
but i need the mean line by distancia and by estado. how can i make it?
thanks.
How about this using stat_summary to plot the means per estado per distancia:
# Generate some sample data
set.seed(2017);
df <- cbind.data.frame(
x = rnorm(100),
estado = sample(c("sana", "lesionada"), 100, replace = T),
distancia = sample(c("0-1", "2.5-3.5", "5.6"), 100, replace = T));
require(ggplot2);
ggplot(df, aes(x = distancia, y = x, colour = estado)) +
geom_point(position = position_dodge(width = 0.3)) +
stat_summary(
fun.y = mean,
geom = "errorbar",
aes(ymax = ..y.., ymin = ..y..),
position = position_dodge(width = 0.3),
width = 0.25);

Adding to ggplot mean and SD plot

I would like to ask for the help.
I am trying to plot data and their mean and SD values on one graph. But I am getting this error
Error in eval(substitute(list(...)), _data, parent.frame()) :
object 'x' not found
First I am dividing data into intervals, and calculate mean and SD values of the intervals using summary. Than I am trying to plot data points (that part works) and add mean and SD value graph to the previous one (here I fail).
Please help me to resolve this issue.
UPD: Ok, I think I should have used stat_summary on the ss data set. Just do not know how to do that at the moment. Any suggestions would be appreciated.
Here is my code:
#Data
s <- data.frame(L5=rnorm(1686, mean=0.3, sd=1.5),
GLDAS=rnorm(1686, mean=0.25, sd=0.8))
#1 )
#Divide data into 0.02 intervals
breaks = seq(from = 0, to = max(s$GLDAS)+0.02, by = 0.02) #intervals
s$group <- cut(s$GLDAS,
breaks = breaks,
labels = seq(from = 1, to = length(breaks)-1, by = 1),
#create label
right = FALSE)
#Assign labels to a value equal to the middle of the interval
pos <- seq(from = breaks[1]+0.02/2, to = max(breaks)-0.02/2, by = 0.02)
group <- seq(from = 1, to = length(breaks)-1, by = 1)
poss <- cbind.data.frame(pos,group)
ss <- merge(s, poss, by = "group")
#Calculate summary
Summary <- ss %>% #
group_by(pos) %>% # the grouping variable
summarise(mean = mean(L5), # calculates the mean of each group
sd = sd(L5), # calculates the standard deviation of each group
n = n(), # calculates the sample size per group
SE = sd(L5)/sqrt(n())) # calculates the standard error of each group
2) #Plot data points
p2 <- ggplot()+
geom_point(data = s, aes(x = GLDAS, y = L5)) +
#geom_smooth(method = "lm", se=FALSE, color="black",
# formula = my.formula) +
stat_poly_eq(formula = my.formula, size = 4,
aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
parse = TRUE) + geom_point()+
geom_abline(intercept=0, slope=1)+
xlim (0,0.6) + ylim(0,0.6) + labs(x="GLDAS [mm/hr]", y="L5 [mm/hr]" ) +
theme(text = element_text(size=16))
3) #plot mean and SD values
p2 + geom_line(data = Summary, aes(x=pos, y=mean), color='blue') +
geom_point(data = Summary, aes(x=pos, y=mean), color='blue')+
geom_errorbar(data = Summary, aes(ymin=mean-sd, ymax=mean+sd), width=.01,
position=position_dodge(0.005), color='blue')
I think I've got it, I did not need to use Summary, there is built in function.
p2 <- ggplot()+
geom_point(data = ss, aes(x = GLDAS, y = L5)) +
stat_poly_eq(formula = my.formula, size = 4,
aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
parse = TRUE) + geom_point()+
geom_abline(intercept=0, slope=1)+
xlim (0,0.5) + ylim(0,0.5) + labs(x="GLDAS [mm/hr]", y="L5 [mm/hr]" ) +
theme(text = element_text(size=16))
p <- p2 + stat_summary(data = ss, aes(x = pos, y = L5),
fun.y = 'mean', fun.ymin = function(x) 0, geom = 'point',
position = 'dodge') +
stat_summary(data = ss, aes(x = pos, y = L5),
fun.y = mean,
fun.ymin = function(y) mean(y) - sd(y),
fun.ymax = function(y) mean(y) + sd(y),
color = "red",
geom ="pointrange",show.legend = FALSE)
p

Resources