Plot Mean & Standard Deviation by Group in R (2 Examples) | Base R & ggplot2 | segments() & axis()

preview_player
Показать описание
R code of this video:

group = LETTERS[1:5])
head(data) # Print head of example data frame

library("dplyr")

data_msd <- data %>% # Get mean & standard deviation by group
group_by(group) %>%
summarise_at(vars(value),
list(mean = mean,
sd = sd)) %>%
data_msd # Print means & standard deviations

plot(1:length(unique(data$group)), # Draw mean values
data_msd$mean,
xlab = "Groups",
ylab = "Mean & Standard Deviation",
xaxt = "n",
ylim = c(min(data_msd$mean - data_msd$sd),
max((data_msd$mean + data_msd$sd))))
segments(x0 = 1:length(unique(data$group)), # Add standard deviations
y0 = data_msd$mean - data_msd$sd,
x1 = 1:length(unique(data$group)),
y1 = data_msd$mean + data_msd$sd)
axis(side = 1, # Add x-axis labels
at = 1:length(unique(data$group)),
labels = data_msd$group)

library("ggplot2") # Load ggplot2 package

ggplot(data_msd, # ggplot2 plot with means & standard deviations
aes(x = group,
y = mean)) +
geom_errorbar(aes(ymin = mean - sd,
ymax = mean + sd)) +
geom_point()

Follow me on Social Media:

Рекомендации по теме