Reputation: 333
I'm a bit new to R and this is the first time I'd like to use ggplot(). My aim is to create a few plots that will look like the template below, which is an output from the package effects
for those who know it:
Given this data:
Average Error Area
1: 0.4407528 0.1853854 Loliondo
2: 0.2895050 0.1945540 Seronera
How can I replicate the plot seen in the image with labels, error bars as in Error
and the line connecting both Average
points?
I hope somebody can put me on the right track and then I will go from there for other data I have.
Any help is appreciated!
Upvotes: 2
Views: 384
Reputation: 1424
Using ggplot2::geom_errorbar
you can add error bars by first deriving your ymin
and ymax
.
df <- tibble::tribble(~Average, ~Error, ~Area,
0.4407528, 0.1853854, "Loliondo",
0.2895050, 0.1945540, "Seronera")
dfnew <- df %>%
mutate(ymin = Average - Error,
ymax = Average + Error)
p <- ggplot(data = dfnew, aes(x = Area, y = Average)) +
geom_point(colour = "blue") + geom_line(aes(group = 1), colour = "blue") +
geom_errorbar(aes(x = Area, ymin = ymin, ymax = ymax), colour = "purple")
Upvotes: 1
Reputation: 1263
Here's a quick and dirty one that is similar to what was just posted:
df <-
tibble(
average = c(0.44, 0.29),
error = c(0.185, 0.195),
area = c("Loliondo", "Seronera")
)
df %>%
ggplot(aes(x = area)) +
geom_line(
aes(y = average, group = 1),
color = "blue"
) +
geom_errorbar(
aes(ymin = average - 0.5 * error, ymax = average + 0.5 * error),
color = "purple",
width = 0.1
)
The trickiest part here is the group = 1
segment, which you need for the line to be drawn with factors on the x axis.
The aes(x = area) goes up top because it's used in both geoms, while the y, group, ymin, and ymax are used only locally. The color and width arguments appear outside of the aes() call since they are used for appearance modifications.
Upvotes: 0