R Language: Ordering Issues in Plotting Categorical Variables

Using the data set mpg that comes with r, a boxplot is drawn to describe the distribution of the number of kilometers (hwy) that can be driven by different car categories (class).


ggplot(data=mpg,mapping=aes(x=class,y=hwy))+
    geom_boxplot()


This box plot is uneven and looks very uncoordinated. If you want to rearrange the order, how to deal with it?

reorder(x, X, FUN = mean, ..., order = is.ordered(x))

x : The categorical variable to be sorted.

X : Sort according to this variable.

FUN : Function to act on X.

ggplot(data = mpg,mapping = aes(x=reorder(class,hwy,FUN=median),y=hwy))+
  geom_boxplot()

 Graphical ordering problems such as bar charts, violin plots, etc. used to plot the distribution of categorical variables can be solved in the same way.

Guess you like

Origin blog.csdn.net/missinghead/article/details/123894240