graph in R with grouping letters from the Tukey, LSD, Duncan test, agricolae package

284 views Asked by At

I would like to produce the following graph enter image description here

with the R package agricolae, could someone give me an example with the attached data?

enter image description here

I expect an adapted graph with the data enter image description here

1

There are 1 answers

1
fborges22 On

Here is an example how to use the agricolae package. This example is normally used on Stocks analysis.

library(agricolae)
library(Quandl)

# Select the stock symbols.
symbols <- c("AAPL", "GOOG", "MSFT", "AMZN", "TSLA")

# Load the closing price data for each stock.
data <- Quandl(symbols, start = "2023-06-01", end = "2023-09-12", type = "close")

# Calculate the mean closing price for each stock.
means <- colMeans(data)

# Plot the bar graph.
bar.group(symbols, means, horiz = FALSE, density = 8, col = "blue", border = "red")

# Add a title and labels.
title("Comparison of stock closing prices")
xlabel("Stock Symbol")
ylabel("Closing Price")

By using your data, your script should be like this:

# Load necessary libraries
install.packages(c("agricolae", "ggplot2"))
library(agricolae)
library(ggplot2)

# Your data
data <- data.frame(
  TREAT = c("t1", "t1", "t1", "t1", "t2", "t2", "t2", "t2", "t3", "t3", "t3", "t3", "t4", "t4", "t4", "t4", "t5", "t5", "t5", "t5"),
  CUT = as.factor(c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)),
  VAR1 = c(16.10, 14.10, 5.80, 4.90, 30.80, 29.00, 28.80, 16.60, 31.30, 29.60, 28.10, 19.50, 21.45, 23.60, 25.95, 28.55, 27.30, 13.70, 8.10, 0.00)
)

# Create a bar plot using ggplot2
plot <- ggplot(data, aes(x = TREAT, y = VAR1, fill = CUT, group = CUT)) +
  geom_bar(stat="identity", position="dodge", width=0.7) +
  labs(title="Bar Plot for Data", y="Value", x="Treatment") +
  theme_minimal()

print(plot)

# Add 'stock' symbols for each bar based on mean comparison
grouping <- with(data, split(VAR1, TREAT))
result <- with(data, bar.group(TREAT, VAR1))
symbols <- result$symbol

# Annotate the bars with 'stock' symbols
data$symbols <- unlist(symbols, use.names = FALSE)
plot + geom_text(aes(label = symbols), position = position_dodge(width = 0.7), vjust=-0.5)