【问题标题】:Tick properties for scatterplot matrices with Matplotlib使用 Matplotlib 标记散点图矩阵的属性
【发布时间】:2013-04-26 17:58:48
【问题描述】:

我正在尝试根据 Joe Kington 编写的代码绘制散点图矩阵:Is there a function to make scatterplot matrices in matplotlib?

有些人已经帮助了我:再次感谢您(尤其是 J.K.)。

我遇到了最后一个问题:我无法旋转数字重叠的某些轴的刻度(左下角):

我想尝试让它们垂直,但我做不到......这是我的代码:

import itertools
import numpy as np
import pylab as plot
import scipy
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import axis
import math
from matplotlib import rc
import os
import platform


def main():
    FigSize=8.89
    FontSize=8
    np.random.seed(1977)
    numvars, numdata = 4, 10
    data = 10 * np.random.random((numvars, numdata))
    fig = scatterplot_matrix(data, ['mpg', 'disp', 'drat', 'wt'], FigSize, FontSize,
        linestyle='none', marker='o', color='black', mfc='none', markersize=3,)
    fig.suptitle('Simple Scatterplot Matrix')
    plt.savefig('Plots/ScatterplotMatrix/ScatterplotMatrix2.pdf',format='pdf', dpi=1000, transparent=True, bbox_inches='tight')
    plt.show()


def scatterplot_matrix(data, names, FigSize, FontSize, **kwargs):
    """Plots a scatterplot matrix of subplots.  Each row of "data" is plotted
    against other rows, resulting in a nrows by nrows grid of subplots with the
    diagonal subplots labeled with "names".  Additional keyword arguments are
    passed on to matplotlib's "plot" command. Returns the matplotlib figure
    object containg the subplot grid."""

    legend=['(kPa)','\%','\%','\%']
    numvars, numdata = data.shape
    fig, axes = plt.subplots(nrows=numvars, ncols=numvars, figsize=(FigSize/2.54,FigSize/2.54))
    fig.subplots_adjust(hspace=0.05, wspace=0.05)

    sub_labelx_top=[2,4]
    sub_labelx_bottom=[13,15]
    sub_labely_left=[5,13]
    sub_labely_right=[4,12]

    for i, ax in enumerate(axes.flat, start=1):
        # Hide all ticks and labels
        ax.xaxis.set_visible(False)
        ax.yaxis.set_visible(False)
        ax.xaxis.set_major_locator(MaxNLocator(prune='both',nbins=4))
        ax.yaxis.set_major_locator(MaxNLocator(prune='both',nbins=4)) #http://matplotlib.org/api/ticker_api.html#matplotlib.ticker.MaxNLocator


        # Set up ticks only on one side for the "edge" subplots...
        if ax.is_first_col():
            ax.yaxis.set_ticks_position('left')
            ax.tick_params(direction='out')
            ax.yaxis.set_tick_params(labelsize=0.75*FontSize)
            if i in sub_labely_left:
        ax.yaxis.set_label_position('left')
            ax.set_ylabel('(\%)',fontsize=0.75*FontSize)

        if ax.is_last_col():
            ax.yaxis.set_ticks_position('right')
            ax.tick_params(direction='out')
            ax.yaxis.set_tick_params(labelsize=0.75*FontSize)
            if i in sub_labely_right:
                ax.yaxis.set_label_position('right')
                if i==4:
                ax.set_ylabel('(kPa)',fontsize=0.75*FontSize)
                else:
                ax.set_ylabel('(\%)',fontsize=0.75*FontSize)

        if ax.is_first_row():
            ax.xaxis.set_ticks_position('top')
            ax.tick_params(direction='out')
            ax.xaxis.set_tick_params(labelsize=0.75*FontSize)
            if i in sub_labelx_top:
                ax.xaxis.set_label_position('top')
                ax.set_xlabel('(\%)',fontsize=0.75*FontSize)

        if ax.is_last_row():
            ax.xaxis.set_ticks_position('bottom')
            ax.tick_params(direction='out')
            ax.xaxis.set_tick_params(labelsize=0.75*FontSize)

            if i in sub_labelx_bottom:
                ax.xaxis.set_label_position('bottom')

                if i==13:
                ax.set_xlabel('(kPa)',fontsize=0.75*FontSize)
                else:
                ax.set_xlabel('(\%)',fontsize=0.75*FontSize)

             # Plot the data.
    for i, j in zip(*np.triu_indices_from(axes, k=1)):
        for x, y in [(i,j), (j,i)]:
            axes[x,y].plot(data[y], data[x], **kwargs)   



    # Label the diagonal subplots...
    for i, label in enumerate(names):
        axes[i,i].annotate(label, (0.5, 0.5), xycoords='axes fraction',
            ha='center', va='center',fontsize=FontSize)

    # Turn on the proper x or y axes ticks.
    for i, j in zip(range(numvars), itertools.cycle((-1, 0))):
        axes[j,i].xaxis.set_visible(True)
        axes[i,j].yaxis.set_visible(True)

    return fig

main()

我的第二个问题更多是为了“有趣”:我怎样才能使子图完美地成正方形?

我向乔·金顿道歉;我知道我的代码没有他的那么优雅......我几周前才开始。如果你有任何改进我的建议,例如让它更有活力,我很感兴趣。

【问题讨论】:

    标签: python properties matplotlib scatter-plot


    【解决方案1】:

    您可以使用setp 旋转xtick 标签。

    from matplotlib.artist import setp
    

    然后在为子图调用的顶行和左列设置 x 刻度位置后:

    setp(ax.get_xticklabels(), rotation=90)
    

    要使子图的大小相等,您可以fig.subplots_adjust 将所有子图的面积设置为正方形。像这样的:

    gridSize = 0.6
    leftBound = 0.5 - gridSize/2
    bottomBound = 0.1
    rightBound = leftBound + gridSize
    topBound = bottomBound + gridSize
    fig.subplots_adjust(hspace=0.05, wspace=0.05, left=leftBound,
                            bottom=bottomBound, right=rightBound, top=topBound)
    

    如果图形大小不是正方形,则需要相应地更改网格的形状。或者,您可以使用fig.add_axes 单独添加每个子图轴。这将允许您直接设置大小,但您还必须设置位置。

    不要使用bbox_inches='tight' 来保存图形,否则您将失去这些设置的标题。你可以这样保存:

    plt.savefig('ScatterplotMatrix.pdf',format='pdf', dpi=1000, transparent=True)
    

    生成的图表如下所示:

    【讨论】:

    • 非常感谢!这正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 2021-10-10
    • 2014-11-09
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    相关资源
    最近更新 更多