code: def reorder(x, y, fun=np.median, ascending=True):
      """
      Reorder categorical by sorting along another variable
  
      It is the order of the categories that changes. Values in x
      are grouped by categories and summarised to determine the
      new order.
  
      Credit: Copied from plydata
  
      Parameters
      ----------
      x : list-like
          Values that will make up the categorical.
      y : list-like
          Values by which `c` will be ordered.
      fun : callable
          Summarising function to `x` for each category in `c`.
          Default is the *median*.
      ascending : bool
          If `True`, the `c` is ordered in ascending order of `x`.
  
      Examples
      --------
      >>> c = list('abbccc')
      >>> x = [11, 2, 2, 3, 33, 3]
      >>> cat_reorder(c, x)
      [a, b, b, c, c, c]
      Categories (3, object): [b, c, a]
      >>> cat_reorder(c, x, fun=max)
      [a, b, b, c, c, c]
      Categories (3, object): [b, a, c]
      >>> cat_reorder(c, x, fun=max, ascending=False)
      [a, b, b, c, c, c]
      Categories (3, object): [c, a, b]
      >>> c_ordered = pd.Categorical(c, ordered=True)
      >>> cat_reorder(c_ordered, x)
      [a, b, b, c, c, c]
      Categories (3, object): [b < c < a]
      >>> cat_reorder(c + ['d'], x)
      Traceback (most recent call last):
          ...
      ValueError: Lengths are not equal. len(c) is 7 and len(x) is 6.
      """
      if len(x) != len(y):
          raise ValueError(
              f"Lengths are not equal. {len(x)=}, {len(x)=}"
          )
      summary = (
          pd.Series(y)
          .groupby(x, observed=True)
          .apply(fun)
          .sort_values(ascending=ascending)
      )
      cats = summary.index.to_list()
      return pd.Categorical(x, categories=cats)
  
file_path: plotnine/plotnine/mapping/evaluation.py
imports: from __future__ import annotations
  import numbers
  import typing
  import numpy
  import pandas
  import pandas.api.types
  from ..exceptions import PlotnineError
label_desc: Use image node_id 3 for calling a global function with example usage: reorder(x, y, fun, ascending) and returns: pd