泰勒图 - 如何显示负相关?蟒蛇

问题描述 投票:0回答:1

我正在尝试编辑代码以显示泰勒图中的负相关性。有人可以阐明我需要在下面的代码中更改什么吗?

我以不同的方式绘制泰勒图,但我无法编辑下面的代码来显示负相关值。

# Função que calcula as métricas.
def make_arrange(taylor_stats, key):
    data = []
    data.append(taylor_stats[0][key][0])
    for stats in taylor_stats:
        data.append(stats[key][1])
    return np.array(data)
    
class TaylorDiagram(object):
    """Taylor diagram: plot model standard deviation and correlation
    to reference (data) sample in a single-quadrant polar plot, with
    r=stddev and theta=arccos(correlation).
    """

    def __init__(self, refstd, fig=None, rect=111, label='_'):
        """Set up Taylor diagram axes, i.e. single quadrant polar
        plot, using mpl_toolkits.axisartist.floating_axes. refstd is
        the reference standard deviation to be compared to.
        """

        from matplotlib.projections import PolarAxes
        import mpl_toolkits.axisartist.floating_axes as FA
        import mpl_toolkits.axisartist.grid_finder as GF

        self.refstd = refstd            # Reference standard deviation

        tr = PolarAxes.PolarTransform()

        # Correlation labels
        rlocs = np.concatenate((np.arange(10)/10.,[0.95,0.99]))
        tlocs = np.arccos(rlocs)        # Conversion to polar angles
        gl1 = GF.FixedLocator(tlocs)    # Positions
        tf1 = GF.DictFormatter(dict(zip(tlocs, map(str,rlocs))))

        # Standard deviation axis extent
        self.smin = 0
        self.smax = 1.5*self.refstd

        ghelper = FA.GridHelperCurveLinear(tr,
                                           extremes=(0,np.pi/2, # 1st quadrant
                                                     self.smin,self.smax),
                                           grid_locator1=gl1,
                                           tick_formatter1=tf1,
                                           )

        if fig is None:
            fig = plt.figure()

        ax = FA.FloatingSubplot(fig, rect, grid_helper=ghelper)
        fig.add_subplot(ax)

        # Adjust axes
        ax.axis["top"].set_axis_direction("bottom")  # "Angle axis"
        ax.axis["top"].toggle(ticklabels=True, label=True)
        ax.axis["top"].major_ticklabels.set_axis_direction("top")
        ax.axis["top"].label.set_axis_direction("top")
        ax.axis["top"].label.set_text("Correlação")

        ax.axis["left"].set_axis_direction("bottom") # "X axis"
        ax.axis["left"].label.set_text("Desvio padrão")

        ax.axis["right"].set_axis_direction("top")   # "Y axis"
        ax.axis["right"].toggle(ticklabels=True)
        ax.axis["right"].major_ticklabels.set_axis_direction("left")

        ax.axis["bottom"].set_visible(False)         # Useless

        # Contours along standard deviations
        ax.grid(False)

        self._ax = ax                   # Graphical axes
        self.ax = ax.get_aux_axes(tr)   # Polar coordinates

        # Add reference point and stddev contour
        print("Reference std:", self.refstd)
        l, = self.ax.plot([0], self.refstd, 'k*',
                          ls='', ms=10, label=label)
        t = np.linspace(0, np.pi/2)
        r = np.zeros_like(t) + self.refstd
        self.ax.plot(t,r, 'k--', label='_')

        # Collect sample points for latter use (e.g. legend)
        self.samplePoints = [l]

    def add_sample(self, stddev, corrcoef, *args, **kwargs):
        """Add sample (stddev,corrcoeff) to the Taylor diagram. args
        and kwargs are directly propagated to the Figure.plot
        command."""

        l, = self.ax.plot(np.arccos(corrcoef), stddev,
                          *args, **kwargs) # (theta,radius)
        self.samplePoints.append(l)

        return l

    def add_contours(self, levels=5, **kwargs):
        """Add constant centered RMS difference contours."""

        rs,ts = np.meshgrid(np.linspace(self.smin,self.smax),
                            np.linspace(-1,np.pi/2))
        # Compute centered RMS difference
        rms = np.sqrt(self.refstd**2 + rs**2 - 2*self.refstd*rs*np.cos(ts))

        contours = self.ax.contour(ts, rs, rms, levels, **kwargs)

        return contours

我的数据是这样的:

OBS     WS100-ACM288    WS100-YSU88     WS100-MYJ88
0   8.287645    9.668434    10.176483   9.114191
1   9.819765    10.781226   10.394920   9.085610
2   10.264626   10.455391   10.750969   10.699900
3   9.936774    8.947848    9.942881    9.323820
4   9.714007    10.384083   10.765621   9.586040
5   8.894456    11.304111   11.176640   10.953554
6   9.368965    11.042116   12.039197   11.292283
7   11.026698   9.868231    9.360654    9.281172
8   9.618249    8.639098    8.571071    8.757381
9   8.057329    6.737832    6.917070    6.154536

然后我绘制:

            obs_key = "OBS"


            # Função para filtar apenas os modelos.
            taylor_stats = [
                sm.taylor_statistics(data[column], data[obs_key])
                for column in data.columns
                if column != obs_key
            ]

            # Armazena os resultados em arranjos de sdev (desvio padrão), 
            # crmsd (erro quadrático médio) e ccoef (correlação).
            sdev = make_arrange(taylor_stats, 'sdev')
            crmsd = make_arrange(taylor_stats, 'crmsd')
            ccoef = make_arrange(taylor_stats, 'ccoef')

            # print(sm.taylor_diagram())  # Descomentar para mais opções de formatação.

            # Rótulos do gráfico.
            label1 = ['WS100-ERA5', "WS100-ACM288", 'WS100-YSU88', 'WS100-MYJ88']
            # Rótulos que vão aparecer na legenda.
            label2 = ["WS100-ACM288", 'WS100-YSU88', 'WS100-MYJ88']

            # Reference dataset
            refstd = data['OBS'].std(ddof=1)           # Reference standard deviation

            # Models
            m1 = data[label2[0]]    # Model 1
            m2 = data[label2[1]]    # Model 2
            m3 = data[label2[2]]    # Model 3

            # Compute stddev and correlation coefficient of models
            samples = np.array([ [m.std(ddof=1), np.corrcoef(data['OBS'], m)[0,1]] for m in (m1,m2,m3)])

            plt.close('all')
            fig = plt.figure(figsize=(5,5))

            # Taylor diagram
            dia = TaylorDiagram(refstd, fig=fig, rect=111, label="OBS")

            colors = plt.matplotlib.cm.jet(np.linspace(0,1,len(samples)))
            # Add samples to Taylor diagram
            for i,(stddev,corrcoef) in enumerate(samples):
                dia.add_sample(stddev, corrcoef, marker=f"${i+1}$", ls='', ms=12, c=colors[i], label=label2[i])

            # Add RMS contours, and label them
            contours = dia.add_contours(colors='0.5')
            plt.clabel(contours, inline=1, fontsize=10)

            ## Add titles
            # plt.title('TMA-CN3: ')

            # Add a figure legend
            fig.legend(dia.samplePoints,
                        [ p.get_label() for p in dia.samplePoints ],
                        numpoints=1, prop=dict(size='small'), loc='upper right',
                        bbox_to_anchor=(1.15,0.9), title=f"24 h")
            
            fig.savefig(f"/media/william/PhD/WRF_88_Ordenado/Previsâo_24h.jpeg", dpi=600, bbox_inches='tight', pad_inches=0.02)

我想在下图中显示负相关性。

python matplotlib correlation diagram
1个回答
0
投票

要绘制负相关性,必须在转换为极角之前在变量

rlocs
中提供负相关性。 在构造函数中包含参数
extend
可以解决问题,
extend = True
可以绘制负相关性,
extend = False
可以仅绘制正相关性。

def __init__(self, refstd,
             fig=None, rect=111, label='_', srange=(0, 1.5), extend=False):
    """
    Set up Taylor diagram axes, i.e. single quadrant polar
    plot, using `mpl_toolkits.axisartist.floating_axes`.
    Parameters:
    * refstd: reference standard deviation to be compared to
    * fig: input Figure or None
    * rect: subplot definition
    * label: reference label
    * srange: stddev axis extension, in units of *refstd*
    * extend: extend diagram to negative correlations
    """

    from matplotlib.projections import PolarAxes
    import mpl_toolkits.axisartist.floating_axes as FA
    import mpl_toolkits.axisartist.grid_finder as GF

    self.refstd = refstd            # Reference standard deviation

    tr = PolarAxes.PolarTransform()

    # Correlation labels
    rlocs = NP.concatenate((np.arange(10)/10.,[0.95,0.99])).tolist()
    if extend:
        # Diagram extended to negative correlations
        self.tmax = NP.pi
        rlocs = NP.concatenate((-rlocs[:0:-1], rlocs))
    else:
        # Diagram limited to positive correlations
        self.tmax = NP.pi/2
    tlocs = NP.arccos(rlocs)        # Conversion to polar angles
    gl1 = GF.FixedLocator(tlocs)    # Positions
    tf1 = GF.DictFormatter(dict(zip(tlocs, map(str, rlocs))))
© www.soinside.com 2019 - 2024. All rights reserved.