I am trying to graph a discrete integer number a
by another discrete number b
. I want to show the median and IQR of b
for each a
with the X-axis sorted by the median of b
. I have used the following code:
a<-sample(1:10, 1000, replace=TRUE)
b <- sample(1:300, 1000, replace=TRUE)
df<-data.frame(a,b)
ggplot(data=df, aes(x = reorder(a, b, median),
y = b)) +
labs(x="a", y="b", title="Variation of b by a") +
stat_summary(fun.y = function(z) { median(z) },
fun.ymin = function(z) { quantile(z, 0.25) },
fun.ymax = function(z) { quantile(z, 0.75) }) +
geom_smooth(method = "lm") +
theme_classic()
And end up with the following result:
This is what I'm looking for except that the last point is not in line with the other points. Why is the last point not sorted properly?