I understand that others have asked this question and I have read and attempted the answers that people have provided, but I'm still not having luck. My R literacy isn't high enough yet and maybe there's something wrong with how I've organised my data?
I have two populations, a and b, and I want to compare leaf length and leaf width on the same boxplot. I can make a qplot of either individually, but not together.
data <- read.csv("Leaf.csv", header=TRUE)
data$AORB <- as.factor(data$AORB)
library(ggplot2); library(plyr)
qplot(mapping=aes(x=AORB,y=Leaf_length),data=data,
main="Box Plot using qplot()",geom="boxplot",
xlab="Country",ylab="Leaf Length")
Here is my data.
structure(list(AORB = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), levels = c("a", "b"), class = "factor"), Leaf_length = c(290L,290L, 350L, 300L, 250L, 510L, 450L, 430L, 550L, 1000L), Leaf_width = c(200L,200L, 280L, 240L, 200L, 190L, 230L, 240L, 250L, 531L)), row.names = c(NA,-10L), class = "data.frame")
Can anyone assist me with the code? Please tell me if I haven't presented my data clearly.
Thank you!
The easiest option to achieve your desired result would be to reshape your data to long before plotting. Also note that qplot
was deprecated in ggplot2 3.4.0
:
library(ggplot2)
library(tidyr)
dat_long <- data |>
tidyr::pivot_longer(c(Leaf_length, Leaf_width),
names_to = "stat", values_to = "value"
)
ggplot(dat_long, aes(AORB, value, fill = stat)) +
geom_boxplot() +
labs(
x = "Country"
)