Looking to label individual boxes in my box-plots created by ggplot. As advised by the answer in this post [Labeling individual boxes in a ggplot boxplot}(https://stackoverflow.com/questions/48029549/labeling-individual-boxes-in-a-ggplot-boxplot) I am using the stat_summary function to do so.
The example code in the forum post:
ggplot(mtcars, aes(factor(cyl), mpg))
geom_boxplot()
stat_summary(geom = 'text', label = letters[1:3], fun.y = max, vjust = -1)
However when I attempt to recreate this for my own plot the labels are out of order. With each boxes' label not being labeled "a", "b", "c", etc.. from left to right as they appear on the plot, but with the "a", "b", "c" labels appearing in alphabetical order of the axis labels. Is there any simple way to correct this?
example of my code:
maxn_topo_plot<- ggplot(wide.df2, aes(x=topo, y=sum_maxn))
geom_boxplot(show.legend = FALSE) theme_pubclean(base_size = 18)
xlab("Island Geomorpholgy") ylab("Shark MaxN")
scale_x_discrete(limits=c("open atoll","closed atoll","near atoll",
"high barrier", "high rocky", "high fringing "))
theme(axis.text.x = element_text(angle = 12))
stat_summary(geom = 'text',
label = c("a","b","c","d", "e", "g"),
fun = max, vjust = -1, size= 6)
maxn_topo_plot
CodePudding user response:
Thats happening because the label() are respecting the factor levels of the variable "topo". Note that the a b c .. order its respecting the alphabetical order.
When you utilize scale_x_discrete to change the order in X axis youre not changing the factor levels order.
Like i sugested in your another question. Change the factor levels of X instead of changing the scale_x_discrete.
maxn_topo_plot<- ggplot(wide.df2, aes(x= factor(topo,
levels = c("open atoll",
"closed atoll",
"near atoll",
"high barrier",
"high rocky",
"high fringing")), y=sum_maxn))
geom_boxplot(show.legend = FALSE)
xlab("Island Geomorpholgy")
ylab("Shark MaxN")
theme_pubclean(base_size = 20)
theme(axis.text.x = element_text(angle = 12))
stat_summary(geom = 'text',
label = c("a","b","c","d", "e", "g"),
fun = max, vjust = -1, size= 6)