code: def traceplot(
      results,
      span=None,
      quantiles=[0.025, 0.5, 0.975],
      smooth=0.02,
      post_color="blue",
      post_kwargs=None,
      kde=True,
      nkde=1000,
      trace_cmap="plasma",
      trace_color=None,
      trace_kwargs=None,
      connect=False,
      connect_highlight=10,
      connect_color="red",
      connect_kwargs=None,
      max_n_ticks=5,
      use_math_text=False,
      labels=None,
      label_kwargs=None,
      show_titles=False,
      title_fmt=".2f",
      title_kwargs=None,
      truths=None,
      truth_color="red",
      truth_kwargs=None,
      verbose=False,
      fig=None,
  ):
      """Plot traces and marginalized posteriors for each parameter.
  
      Parameters
      ----------
      results : `~dynesty.results.Results` instance
          A `~dynesty.results.Results` instance from a nested
          sampling run. **Compatible with results derived from**
          `nestle <http://kylebarbary.com/nestle/>`_.
      span : iterable with shape (ndim,), optional
          A list where each element is either a length-2 tuple containing
          lower and upper bounds or a float from `(0., 1.]` giving the
          fraction of (weighted) samples to include. If a fraction is provided,
          the bounds are chosen to be equal-tailed. An example would be::
  
              span = [(0., 10.), 0.95, (5., 6.)]
  
          Default is `0.999999426697` (5-sigma credible interval) for each
          parameter.
      quantiles : iterable, optional
          A list of fractional quantiles to overplot on the 1-D marginalized
          posteriors as vertical dashed lines. Default is `[0.025, 0.5, 0.975]`
          (the 95%/2-sigma credible interval).
      smooth : float or iterable with shape (ndim,), optional
          The standard deviation (either a single value or a different value for
          each subplot) for the Gaussian kernel used to smooth the 1-D
          marginalized posteriors, expressed as a fraction of the span.
          Default is `0.02` (2% smoothing). If an integer is provided instead,
          this will instead default to a simple (weighted) histogram with
          `bins=smooth`.
      post_color : str or iterable with shape (ndim,), optional
          A `~matplotlib`-style color (either a single color or a different
          value for each subplot) used when plotting the histograms.
          Default is `'blue'`.
      post_kwargs : dict, optional
          Extra keyword arguments that will be used for plotting the
          marginalized 1-D posteriors.
      kde : bool, optional
          Whether to use kernel density estimation to estimate and plot
          the PDF of the importance weights as a function of log-volume
          (as opposed to the importance weights themselves). Default is
          `True`.
      nkde : int, optional
          The number of grid points used when plotting the kernel density
          estimate. Default is `1000`.
      trace_cmap : str or iterable with shape (ndim,), optional
          A `~matplotlib`-style colormap (either a single colormap or a
          different colormap for each subplot) used when plotting the traces,
          where each point is colored according to its weight. Default is
          `'plasma'`.
      trace_color : str or iterable with shape (ndim,), optional
          A `~matplotlib`-style color (either a single color or a
          different color for each subplot) used when plotting the traces.
          This overrides the `trace_cmap` option by giving all points
          the same color. Default is `None` (not used).
      trace_kwargs : dict, optional
          Extra keyword arguments that will be used for plotting the traces.
      connect : bool, optional
          Whether to draw lines connecting the paths of unique particles.
          Default is `False`.
      connect_highlight : int or iterable, optional
          If `connect=True`, highlights the paths of a specific set of
          particles. If an integer is passed, :data:`connect_highlight`
          random particle paths will be highlighted. If an iterable is passed,
          then the particle paths corresponding to the provided indices
          will be highlighted.
      connect_color : str, optional
          The color of the highlighted particle paths. Default is `'red'`.
      connect_kwargs : dict, optional
          Extra keyword arguments used for plotting particle paths.
      max_n_ticks : int, optional
          Maximum number of ticks allowed. Default is `5`.
      use_math_text : bool, optional
          Whether the axis tick labels for very large/small exponents should be
          displayed as powers of 10 rather than using `e`. Default is `False`.
      labels : iterable with shape (ndim,), optional
          A list of names for each parameter. If not provided, the default name
          used when plotting will follow :math:`x_i` style.
      label_kwargs : dict, optional
          Extra keyword arguments that will be sent to the
          `~matplotlib.axes.Axes.set_xlabel` and
          `~matplotlib.axes.Axes.set_ylabel` methods.
      show_titles : bool, optional
          Whether to display a title above each 1-D marginalized posterior
          showing the 0.5 quantile along with the upper/lower bounds associated
          with the 0.025 and 0.975 (95%/2-sigma credible interval) quantiles.
          Default is `True`.
      title_fmt : str, optional
          The format string for the quantiles provided in the title. Default is
          `'.2f'`.
      title_kwargs : dict, optional
          Extra keyword arguments that will be sent to the
          `~matplotlib.axes.Axes.set_title` command.
      truths : iterable with shape (ndim,), optional
          A list of reference values that will be overplotted on the traces and
          marginalized 1-D posteriors as solid horizontal/vertical lines.
          Individual values can be exempt using `None`. Default is `None`.
      truth_color : str or iterable with shape (ndim,), optional
          A `~matplotlib`-style color (either a single color or a different
          value for each subplot) used when plotting `truths`.
          Default is `'red'`.
      truth_kwargs : dict, optional
          Extra keyword arguments that will be used for plotting the vertical
          and horizontal lines with `truths`.
      verbose : bool, optional
          Whether to print the values of the computed quantiles associated with
          each parameter. Default is `False`.
      fig : (`~matplotlib.figure.Figure`, `~matplotlib.axes.Axes`), optional
          If provided, overplot the traces and marginalized 1-D posteriors
          onto the provided figure. Otherwise, by default an
          internal figure is generated.
  
      Returns
      -------
      traceplot : (`~matplotlib.figure.Figure`, `~matplotlib.axes.Axes`)
          Output trace plot.
  
      """
      # Initialize values.
      if title_kwargs is None:
          title_kwargs = dict()
      if label_kwargs is None:
          label_kwargs = dict()
      if trace_kwargs is None:
          trace_kwargs = dict()
      if connect_kwargs is None:
          connect_kwargs = dict()
      if post_kwargs is None:
          post_kwargs = dict()
      if truth_kwargs is None:
          truth_kwargs = dict()
  
      # Set defaults.
      connect_kwargs["alpha"] = connect_kwargs.get("alpha", 0.7)
      post_kwargs["alpha"] = post_kwargs.get("alpha", 0.6)
      trace_kwargs["s"] = trace_kwargs.get("s", 3)
      truth_kwargs["linestyle"] = truth_kwargs.get("linestyle", "solid")
      truth_kwargs["linewidth"] = truth_kwargs.get("linewidth", 2)
  
      # Extract weighted samples.
      samples = results["samples"]
      logvol = results["logvol"]
      weights = results["weights"]
  
      wts = weights
      kde = kde and (weights * len(logvol) > 0.1).sum() > 10
      if kde:
          try:
              from scipy.ndimage import gaussian_filter as norm_kde
              from scipy.stats import gaussian_kde
  
              # Derive kernel density estimate.
              wt_kde = gaussian_kde(
                  resample_equal(-logvol, weights)
              )  # KDE
              logvol_grid = np.linspace(
                  logvol[0], logvol[-1], nkde
              )  # resample
              wt_grid = wt_kde.pdf(-logvol_grid)  # evaluate KDE PDF
              wts = np.interp(
                  -logvol, -logvol_grid, wt_grid
              )  # interpolate
          except ImportError:
              kde = False
  
      # Deal with 1D results. A number of extra catches are also here
      # in case users are trying to plot other results besides the `Results`
      # instance generated by `dynesty`.
      samples = np.atleast_1d(samples)
      if len(samples.shape) == 1:
          samples = np.atleast_2d(samples)
      else:
          assert len(samples.shape) == 2, "Samples must be 1- or 2-D."
          samples = samples.T
      assert (
          samples.shape[0] <= samples.shape[1]
      ), "There are more dimensions than samples!"
      ndim, nsamps = samples.shape
  
      # Check weights.
      if weights.ndim != 1:
          raise ValueError("Weights must be 1-D.")
      if nsamps != weights.shape[0]:
          raise ValueError(
              "The number of weights and samples disagree!"
          )
  
      # Check ln(volume).
      if logvol.ndim != 1:
          raise ValueError("Ln(volume)'s must be 1-D.")
      if nsamps != logvol.shape[0]:
          raise ValueError(
              "The number of ln(volume)'s and samples disagree!"
          )
  
      # Check sample IDs.
      if connect:
          try:
              samples_id = results["samples_id"]
              uid = np.unique(samples_id)
          except Exception:
              raise ValueError("Sample IDs are not defined!")
          try:
              ids = connect_highlight[0]
              ids = connect_highlight
          except Exception:
              ids = np.random.choice(
                  uid, size=connect_highlight, replace=False
              )
  
      # Determine plotting bounds for marginalized 1-D posteriors.
      if span is None:
          span = [0.999999426697 for i in range(ndim)]
      span = list(span)
      if len(span) != ndim:
          raise ValueError(
              "Dimension mismatch between samples and span."
          )
      for i, _ in enumerate(span):
          try:
              xmin, xmax = span[i]
          except Exception:
              q = [0.5 - 0.5 * span[i], 0.5 + 0.5 * span[i]]
              span[i] = _quantile(samples[i], q, weights=weights)
  
      # Setting up labels.
      if labels is None:
          labels = [r"$x_{%d}$" % (i + 1) for i in range(ndim)]
  
      # Setting up smoothing.
      if isinstance(smooth, int_type) or isinstance(smooth, float_type):
          smooth = [smooth for i in range(ndim)]
  
      # Setting up default plot layout.
      if fig is None:
          fig, axes = pl.subplots(ndim, 2, figsize=(12, 3 * ndim))
      else:
          fig, axes = fig
          try:
              axes.reshape(ndim, 2)
          except Exception:
              raise ValueError(
                  "Provided axes do not match the required shape "
                  "for plotting samples."
              )
  
      # Plotting.
      for i, x in enumerate(samples):
          # Plot trace.
  
          # Establish axes.
          if np.shape(samples)[0] == 1:
              ax = axes[1]
          else:
              ax = axes[i, 0]
          # Set color(s)/colormap(s).
          if trace_color is not None:
              if isinstance(trace_color, str_type):
                  color = trace_color
              else:
                  color = trace_color[i]
          else:
              color = wts
          if isinstance(trace_cmap, str_type):
              cmap = trace_cmap
          else:
              cmap = trace_cmap[i]
          # Setup axes.
          ax.set_xlim([0.0, -min(logvol)])
          ax.set_ylim([min(x), max(x)])
          if max_n_ticks == 0:
              ax.xaxis.set_major_locator(NullLocator())
              ax.yaxis.set_major_locator(NullLocator())
          else:
              ax.xaxis.set_major_locator(MaxNLocator(max_n_ticks))
              ax.yaxis.set_major_locator(MaxNLocator(max_n_ticks))
          # Label axes.
          sf = ScalarFormatter(useMathText=use_math_text)
          ax.yaxis.set_major_formatter(sf)
          ax.set_xlabel(r"$-\ln X$", **label_kwargs)
          ax.set_ylabel(labels[i], **label_kwargs)
          # Generate scatter plot.
          ax.scatter(-logvol, x, c=color, cmap=cmap, **trace_kwargs)
          if connect:
              # Add lines highlighting specific particle paths.
              for j in ids:
                  sel = samples_id == j
                  ax.plot(
                      -logvol[sel],
                      x[sel],
                      color=connect_color,
                      **connect_kwargs,
                  )
          # Add truth value(s).
          if truths is not None and truths[i] is not None:
              try:
                  [
                      ax.axhline(t, color=truth_color, **truth_kwargs)
                      for t in truths[i]
                  ]
              except Exception:
                  ax.axhline(
                      truths[i], color=truth_color, **truth_kwargs
                  )
  
          # Plot marginalized 1-D posterior.
  
          # Establish axes.
          if np.shape(samples)[0] == 1:
              ax = axes[0]
          else:
              ax = axes[i, 1]
          # Set color(s).
          if isinstance(post_color, str_type):
              color = post_color
          else:
              color = post_color[i]
          # Setup axes
          ax.set_xlim(span[i])
          if max_n_ticks == 0:
              ax.xaxis.set_major_locator(NullLocator())
              ax.yaxis.set_major_locator(NullLocator())
          else:
              ax.xaxis.set_major_locator(MaxNLocator(max_n_ticks))
              ax.yaxis.set_major_locator(NullLocator())
          # Label axes.
          sf = ScalarFormatter(useMathText=use_math_text)
          ax.xaxis.set_major_formatter(sf)
          ax.set_xlabel(labels[i], **label_kwargs)
          # Generate distribution.
          s = smooth[i]
          if isinstance(s, int_type):
              # If `s` is an integer, plot a weighted histogram with
              # `s` bins within the provided bounds.
              n, b, _ = ax.hist(
                  x,
                  bins=s,
                  weights=weights,
                  color=color,
                  range=np.sort(span[i]),
                  **post_kwargs,
              )
              x0 = np.array(list(zip(b[:-1], b[1:]))).flatten()
              y0 = np.array(list(zip(n, n))).flatten()
          else:
              # If `s` is a float, oversample the data relative to the
              # smoothing filter by a factor of 10, then use a Gaussian
              # filter to smooth the results.
              if kde:
                  bins = int(round(10.0 / s))
                  n, b = np.histogram(
                      x,
                      bins=bins,
                      weights=weights,
                      range=np.sort(span[i]),
                  )
                  x0 = 0.5 * (b[1:] + b[:-1])
                  n = norm_kde(n, 10.0)
                  y0 = n
                  ax.fill_between(x0, y0, color=color, **post_kwargs)
              else:
                  bins = 40
                  n, b = np.histogram(
                      x,
                      bins=bins,
                      weights=weights,
                      range=np.sort(span[i]),
                  )
                  x0 = 0.5 * (b[1:] + b[:-1])
                  y0 = n
                  ax.fill_between(x0, y0, color=color, **post_kwargs)
          ax.set_ylim([0.0, max(y0) * 1.05])
          # Plot quantiles.
          if quantiles is not None and len(quantiles) > 0:
              qs = _quantile(x, quantiles, weights=weights)
              for q in qs:
                  ax.axvline(q, lw=2, ls="dashed", color=color)
              if verbose:
                  print("Quantiles:")
                  print(
                      labels[i], [blob for blob in zip(quantiles, qs)]
                  )
          # Add truth value(s).
          if truths is not None and truths[i] is not None:
              try:
                  [
                      ax.axvline(t, color=truth_color, **truth_kwargs)
                      for t in truths[i]
                  ]
              except Exception:
                  ax.axvline(
                      truths[i], color=truth_color, **truth_kwargs
                  )
          # Set titles.
          if show_titles:
              title = None
              if title_fmt is not None:
                  ql, qm, qh = _quantile(
                      x, [0.025, 0.5, 0.975], weights=weights
                  )
                  q_minus, q_plus = qm - ql, qh - qm
                  fmt = "{{0:{0}}}".format(title_fmt).format
                  title = r"${{{0}}}_{{-{1}}}^{{+{2}}}$"
                  title = title.format(
                      fmt(qm), fmt(q_minus), fmt(q_plus)
                  )
                  title = "{0} = {1}".format(labels[i], title)
                  ax.set_title(title, **title_kwargs)
  
      return fig, axes
  
imports: from __future__ import print_function, division
  from six.moves import range
  import logging
  import types
  import warnings
  import numpy
  import matplotlib.pyplot
  from matplotlib.ticker import MaxNLocator, NullLocator
  from matplotlib.ticker import ScalarFormatter
  import scipy.stats
  import matplotlib.pyplot
  import numpy
  from .utils import resample_equal
  from .utils import quantile
  import corner
label_desc: Use image node_id 3 for calling a global function with example usage: traceplot(results, span, quantiles, smooth, post_color, post_kwargs, kde, nkde, trace_cmap, trace_color, trace_kwargs, connect, connect_highlight, connect_color, connect_kwargs, max_n_ticks, use_math_text, labels, label_kwargs, show_titles, title_fmt, title_kwargs, truths, truth_color, truth_kwargs, verbose, fig) and returns: fig,  axes