3
I intend to connect a line connecting several boxplots on R
. I’ve tried using the functions abline
and lines
, but I did not succeed. How can I solve my problem?
3
I intend to connect a line connecting several boxplots on R
. I’ve tried using the functions abline
and lines
, but I did not succeed. How can I solve my problem?
8
As no data was provided to solve the problem, I will use the data set iris
to solve it. This data set has 150 observations on 4 quantitative variables and 1 categorical. This categorical variable has three levels. Because of these characteristics, this data set becomes very interesting to illustrate how to solve this problem.
Also, I will solve it in two ways: with the function boxplot
, which is standard of R
, and with the package ggplot2
.
First we need to plot the simple boxplot, using a quantitative variable as response and a categorical variable as predictor:
boxplot(Petal.Length ~ Species, data=iris)
Next, it is necessary to calculate the median for each plant species, so that the boxplots are connected according to some criterion. One way to do this is with the Aggregate function:
aggregate(iris$Petal.Length, list(iris$Species), median)
Group.1 x
1 setosa 1.50
2 versicolor 4.35
3 virginica 5.55
For the graph to come out more easily, I will save this result inside an object called medianas
. From that, just use lines
and plot the averages calculated on top of the generated boxplot, considering that each variable level Species
can be understood as a number from 1 to 3:
medianas <- aggregate(iris$Petal.Length, list(iris$Species), median)
lines(1:3, medianas$x)
ggplot2
I find this solution more elegant because the ggplot2
calculates and plots alone the statistics we want to put on the chart. To do this, just use the function stat_summary
:
library(ggplot2)
ggplot(iris, aes(x=Species, y=Petal.Length)) +
geom_boxplot() +
stat_summary(fun.y=median, geom="line", lwd=1, aes(group=1))
Browser other questions tagged r
You are not signed in. Login or sign up in order to post.
Put the code and an example, this will facilitate the response.
– Márcio Mocellin