def distance_of_partition(agglomerative_matrix, n_communities):
    """ Returns the distance of the partition from the ground level.

    The partition considered is the one which splits the graph into
    `n_communities` different communities.

    Parameters
    ----------
    agglomerative_matrix: numpy.ndarray
        Matrix which encodes the hierarchical clustering to render as
        a dendrogram. The hierarchical clustering is detected using the
        Girvan-Newman algorithm. See the `agglomerative_matrix` function
        for more information on the format of `agglomerative_matrix`.

    n_comunities: integer
        The number of communities into which the partition we are
        interested in is split.

    Returns
    -------
    integer
        Distance of the partition we are interested in from the ground level.
        Which is the distance from the hierarchy level where all nodes are
        disconnected.

    Raises
    ------
    TypeError
        If n_communities does not belong to [1, number_nodes]

    Example
    --------
    To get the distance of the partition with 2 communities from the
    ground level::

        >>> G = nx.path_graph(6)
        >>> partitions = girvan_newman_partitions(G)
        >>> agglomerative_mat = agglomerative_matrix(G, partitions)
        >>> n_communities = 2
        >>> dist_2comm = distance_of_partition(agglomerative_mat,
                                               n_communities)
        >>> print (dist_2comm)
        ... 3

    To plot the dendrogram highlighting the partition which splits the graph
    into 2 communities::

        >>> from scipy.cluster.hierarchy import dendrogram
        >>> dendro_2comm = dendrogram(agglomerative_mat,
                                      color_threshold=dist_2comm)

     """
    # Check if 'n_communities' belongs to the interval [1, number_nodes].
    nn = len(agglomerative_matrix[:, 0]) + 1
    if (n_communities < 1) or (n_communities > nn):
        raise TypeError('Bad number of communities: n_communities must be' +
                        ' an integer between 1 and number_nodes')

    # High of the level of the hierarchy in which the graph is split
    # into 'n_communities' different partitions.
    high_max = int(agglomerative_matrix[-1, 2])
    partition_height = high_max - (n_communities - 2)

    return partition_height