Creating Error Bars in R (ggplot2) - r

I've been working on creating a bar graph with error bars to depict group differences for a dataset that I have. But the error bars are coming out funky, in that they are appearing further above the bar and in the middle of a bar.
My code:
ggplot(MRS_Hippo_NAA_Cre_Data_copy, aes(Type, Hippo_6_9NAACre, fill=Type)) +
geom_bar(stat="summary", fun.y="mean", colour="black", size=.3) +
geom_errorbar(aes(ymin=meanNAA-NAAse, ymax=meanNAA+NAAse), width=.2,
position=position_dodge(.9)) + labs(x="Group", y="Right Posterior NAA/Cre") +
scale_fill_manual(values=c("#0072B2", "#D55E00"), name="Group") + theme(text =
element_text(size=18))`
This produced this graph:
I calculated the standard error by using the following function:
std <- function(x) sd(x)/sqrt(length(x))
x=Hippo_6_9NAACre
Not sure why the graph is producing funky error bars. Can anyone help or provide insight?

I had very recently a similar problem.
To solve it, first of all you may want to remove the layer
geom_errorbar(aes(ymin=meanNAA-NAAse,
ymax=meanNAA+NAAse), width=.2, position=position_dodge(.9))
and rather use a layer with the statsummary function again. That will generate the error bars separated for group.
As you want the bars indicating the standard error, you must create an appropriate function that returns the needed values, such that can be used from statsummary.
Find below a working example with iris dataset.
library(ggplot2)
## create a function for standard error that can be used with stat_summary
# I created the function inspecting the results returned by 'mean_cl_normal' that is the
# function used in some examples of stat_summary (see ?stat_summary).
mean_se = function(x){
se = function(x){sd(x)/sqrt(length(x))}
data.frame(y=mean(x), ymin=mean(x)+se(x), ymax=mean(x)-se(x))
}
## create the plot
p = ggplot(iris, aes(x = Species, y = Sepal.Length), stat="identity") +
stat_summary(fun.y = mean, geom = "col", fill = "White", colour = "Black", width=0.5) +
stat_summary(fun.data = mean_se, geom = "errorbar", width=0.2, size=1)
# print the plot
print(p)

Related

Arranging plots using grid.arrange R

I have six plots obtained with ggplot2 for normality analysis: 2 histograms, 2 qqplots and 2 boxplots.
I want to display them together ordered by type of plot: so the histograms in the first row, the qqplots in the second row and the boxplots in the third row. For this I use the grid.arrange function from gridExtra package as follows:
grid.arrange(grobs= list(plot1, plot2, qqplot1, qqplot2, boxplot1, boxplot2),
ncol=2, nrow=3,
top = ("Histograms + Quantile Graphics + Boxplots"))
But this error message pops up:
Error: stat_bin() requires an x or y aesthetic.
any idea how to solve this?
As people said in the comments the error was the aes() of one of the plots. The confussion came as R allows you to create an object even when it´s not operational, I guess this is because it can be modified later. This is the code for the plot:
ggplot(data = mtcars, aes(sample=mtcars$mpg)) +
geom_histogram(aes(y = ..density.., fill = ..count..), binwidth = 1) +
geom_density(alpha=.2) +
scale_fill_gradient(low = "#6ACE78", high = "#0D851D") +
stat_function(fun = dnorm, colour = "firebrick",
args = list(mean = mean(mtcars$mpg),
sd = sd(mtcars$mpg))) +
labs(x = "Tiempo de seguimiento", y = "")+
theme_bw()
As you can see, the mistake is the first aes() argument, as I wrote sample= instead of x=. Already solved.
Thanks

Putting error bars on jittered points in R

I'm trying to plot a scatter graph with error bars in R using categorical data on the x axis, using the following code:
Nesk <- read.table("E:\\R stuff\\Chapter 2\\Boxplots of nb\\NEnbNOINF.txt", header=TRUE, fill=TRUE)
pd <- position_dodge(0.2)
ggplot(Nesk, aes(x = TYPE, y = NB, color = TYPE)) +
geom_jitter() +
geom_point(position = pd) +
geom_errorbar(aes(ymin = LC, ymax = UC), position = pd) +
theme_bw() +
theme(axis.title = element_text(face = "bold")) +
ylab("Nb")
However, I can't get the error bars on the jittered points. I end up with this https://imgur.com/qBcvOat. Sorry all, don't have the reputation to directly insert images
I've tried using position dodge however I'm aware that it just separates the points by category (COL, LIN, NOM) as opposed to within each category. Is there any way I can jitter the points and attach error bars to these? I've seen some posts with fixes for this, but I think somewhere along the line an update invalidated those.
Thanks in advance!

ggplot2 facet_wrap doesn't find a variable but shape does

I'm running in a bit of a problem plotting some data with ggplot2: I want to use a facet_wrap over a variable AdultInputProp, but R doesn't find the variable and instead returns an Error in as.quoted(facets) : object 'AdultInputProp' not found. Now I understand that this simply means that R can't find this variable in the dataset used to plot, but if I ask ggplot2 to instead use the same variable for to create a shape scale, it works just fine. Any idea what the problem might be?
Sorry, I'm not too sure how to make a minimal working example with a generated df from scratch, so here's the df I'm using, and the code bellow. I've also tried using facet_grid instead of facet_wrap but ran into the same problem.
The code here with facets returns the above-mentioned error:
df.plot.GBPperAIP <- ggplot(df.sum.GBPperAIP,
aes(x=TestIteration, y=Error,
colour=GoalBabblingProp,
group=interaction(GoalBabblingProp,
AdultInputProp))) +
facet_wrap(AdultInputProp) +
xlab("Step") + ylab("Mean error") + theme_bw(base_size=18) +
scale_colour_discrete(name = "Goal babbling proportion") +
geom_line(position = position_dodge(1000)) +
geom_errorbar(aes(ymin=Error-ci,
ymax=Error+ci),
color="black", width=1000,
position = position_dodge(1000)) +
geom_point(position = position_dodge(1000),
size=1.5, fill="white")
This other code, exactly the same except for the facet_wrap line deleted and with shape added works fine:
df.plot.GBPperAIP <- ggplot(df.sum.GBPperAIP,
aes(x=TestIteration, y=Error,
colour=GoalBabblingProp,
shape=AdultInputProp,
group=interaction(GoalBabblingProp,
AdultInputProp))) +
xlab("Step") + ylab("Mean error") + theme_bw(base_size=18) +
scale_colour_discrete(name = "Goal babbling proportion") +
geom_line(position = position_dodge(1000)) +
geom_errorbar(aes(ymin=Error-ci,
ymax=Error+ci),
color="black", width=1000,
position = position_dodge(1000)) +
geom_point(position = position_dodge(1000),
size=1.5, fill="white")
facet_wrap expects a formula, not just a naked variable name. So you should change it to
...
facet_wrap(~ AdultInputProp) +
...

ggplot2 graph and overriding

I have recently started using ggplot2 so, I once again apologize for posting basic question.
I read about this code in one of the help pages. This code nicely plots line graph and the average with red dot:
ggplot(mpg, aes(trans, cty)) +
geom_point() +
stat_summary(geom = "point", fun.y = "mean", colour = "red", size = 4)
I thought of simplifying this a bit by overriding the contents of geom_point() and using stat="summary"
ggplot(mpg, aes(trans, cty)) +
geom_point(stat = "summary", fun.y = "mean", colour = "red", size = 4) +
However, the above code doesn't work. Can someone please help me why above code doesn't work? Specifically, it only plots the red dot (mean point). I don't see the scatterplot although I have used geom_point()
Because ggplot() defines aes(), but you are overriding them using the geom layer.
In the first case, geom_point() completes the plotting of the points, and stat_summary() did the part of adding summary statistics layer to your graph.
But, when you define stat = "summary", you tell geom_point() to plot summary statistics instead of the data points.
Head over the ggplot2 documentation and read how mapping works within this ecosystem: http://docs.ggplot2.org/current/

Creating histogram on R

I am trying to create a graph on R but keep getting this error...
Error in inherits(mapping, "uneval") : object 'EI.TOT' not found
I have put in this command:
hist.1 <- ggplot(data, EI.TOT) + theme(legend.position = "none") + geom_histogram(aes(y=..density..), colour="black", fill="white") + labs(x="EI.TOT", y = "Density")
EI.TOT is the header of one of my columns. I have run a regression using these values but when I want to create a histogram is says that this column is not found.
Your trouble is that you dont specify your aes correctly. Try this code, let me know if it does not work on your data.
library(ggplot2)
data <- data.frame(EI.TOT =rnorm(60))
hist.1 <- ggplot(data=data) +
theme(legend.position = "none") +
geom_histogram(aes(EI.TOT),colour="black", fill="white", binwidth = 0.5) +
labs(x="EI.TOT", y = "Density")
hist.1
Change bindwidth to change the breaks in the plot.

Resources