Points in Boxplot are crooked

Hi there, I produced a boxplot where I would like to include the mean of each category, marked by a point. Though my code works, the points look crooked, as can be seen in the picture I attached. This happens in R studio as well as in the exported image. It doesn't matter how high the resolution is set or which point I use (also tried pch= 18, pch=23, and a few others...). Does any of you know the reason for this or how I can fix it?

Thank you so much!

(I know this code might not be the most efficient, I don't work with R on a daily basis).

boxplot(y ~ x, data=mydata, na.rm=T, col=c("slategray1", "slategray1", "slategray1", "slategray1", "slategray2")) 
means <- by(mydata$y, mydata$x, mean, na.rm=T)
points(1:5, means, pch = 5)
text(1:5, means, labels =c("Mean 2.60", "Mean 2.31", "Mean 2.53", "Mean 2.41", "Mean 2.55"), pos = 3)

You haven't provided your data, so we can't reproduce your actual boxplot. However, I note that it does look weird (the median lines are all at the margin of the boxes, and the ranges are all identical).

Here is a reproducible example that uses the iris dataset, and png() to save a high-quality (600 dpi) image file (my_graph.png) , where the symbols look great (even at very high magnification). Import the file into your-favourite-word-processor to see. Code assumes you are running under Windows.

I have removed the median lines as they will often overlap with a mean point (you can keep the notch, or not, as required).

data(iris)
my_means <- by(iris$Sepal.Width, iris$Species, mean, na.rm=TRUE)
my_means
#> iris$Species: setosa
#> [1] 3.428
#> -------------------------------------------------------- 
#> iris$Species: versicolor
#> [1] 2.77
#> -------------------------------------------------------- 
#> iris$Species: virginica
#> [1] 2.974

my_labels <- paste0("Mean ",my_means)
my_labels
#> [1] "Mean 3.428" "Mean 2.77"  "Mean 2.974"

boxplot(Sepal.Width ~ Species,
        data=iris,
        notch=TRUE,
        medlty = "blank",
        col=c("slategray1", "slategray2", "slategray3")) 

points(1:3, my_means, pch=19, cex=1.1)
text(1:3, my_means, labels=my_labels, pos=3, cex=0.9)

# OK, when graph looks OK, send it to a high-quality PNG file for use in Word documents etc.
png(file="my_graph.png", res=600, width=4800, height=4800, pointsize=10,
        type="windows", antialias="cleartype")
  boxplot(Sepal.Width ~ Species,
          data=iris,
          notch=TRUE,
          medlty = "blank",
          col=c("slategray1", "slategray2", "slategray3")) 
  
  points(1:3, my_means, pch=19, cex=1.1)
  text(1:3, my_means, labels=my_labels, pos=3, cex=0.9)
dev.off()
#> png 
#>   2

# Or use svg() if you prefer
?svg

# Or use ggplot2 and ggsave()
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.