【问题标题】:How do I make a matplotlib scatter plot square?如何制作 matplotlib 散点图正方形?
【发布时间】:2016-07-18 21:31:22
【问题描述】:

在 gnuplot 中,我可以这样做得到一个正方形图:

set size square

matplotlib 中的等价物是什么?我试过这个:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.rcParams['backend'] = 'TkAgg'
x = [0, 0.2, 0.4, 0.6, 0.8]
y = [0, 0.5, 1, 1.5, 2.0]
colors = ['k']*len(x)
plt.scatter(x, y, c=colors, alpha=0.5)
plt.axes().set_aspect('equal', adjustable='datalim')
plt.xlim((0,2))
plt.ylim((0,2))
plt.grid(b=True, which='major', color='k', linestyle='--')
plt.savefig('{}.png'.format(rsID), dpi=600)
plt.close()
plt.clf()

我得到一个方形网格,但情节本身不是方形的。如何使 x 范围从 0 到 2 并使绘图呈正方形?

【问题讨论】:

    标签: python matplotlib plot scatter-plot aspect-ratio


    【解决方案1】:

    你可以这样做:

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    x = [0, 0.2, 0.4, 0.6, 0.8]
    y = [0, 0.5, 1, 1.5, 2.0]
    colors = ['k']*len(x)
    ax.scatter(x, y, c=colors, alpha=0.5)
    ax.set_xlim((0,2))
    ax.set_ylim((0,2))
    x0,x1 = ax.get_xlim()
    y0,y1 = ax.get_ylim()
    ax.set_aspect(abs(x1-x0)/abs(y1-y0))
    ax.grid(b=True, which='major', color='k', linestyle='--')
    fig.savefig('test.png', dpi=600)
    plt.close(fig)
    

    【讨论】:

    • 至少到现在(2020 年 2 月),您可以使用 set_aspect('equal') 来获得«从数据到 x 和 y 的绘图单位的相同缩放»以提供相同的结果。
    【解决方案2】:

    设置图中的大小:

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    plt.rcParams['backend'] = 'TkAgg'
    x = [0, 0.2, 0.4, 0.6, 0.8]
    y = [0, 0.5, 1, 1.5, 2.0]
    colors = ['k']*len(x)
    fig = plt.figure(figsize=(6,6)) # default is (8,6)
    ax = fig.add_subplot(111, aspect='equal')
    ax.scatter(x, y, c=colors, alpha=0.5)
    ax.set_xlim((0,2))
    ax.set_ylim((0,2))
    ax.grid(b=True, which='major', color='k', linestyle='--')
    

    【讨论】:

    • 投反对票的人是否愿意解释原因?
    • 不是我,但我认为您所做的只是将画布大小设置为相等,而没有将实际绘图区域设置为正方形。它可能会被轴和刻度标签等弄乱,因为 matplotlib 会缩小绘图区域以将这些东西放在画布上。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-31
    • 1970-01-01
    • 2021-09-04
    • 2013-08-29
    • 1970-01-01
    相关资源
    最近更新 更多