在散点图中,将每个网格单元格设置为python 3.2中matplotlib中的正方形

时间:2015-07-24 22:32:52

标签: python python-3.x matplotlib scatter

我需要在python 3.2中使用matplotlib绘制2D散点图。

但是,数据的最大值和最小值非常大。

我需要调整网格和代码,以便每个网格单元格都是正方形,连接到代码的网格线数量应取决于图形的大小。

更新

我更喜欢分别在X轴和Y轴上的n X n网格线。 n的值取决于X和Y的最大值。我想将n保持在3到8之间。这意味着在X和Y方向上不超过8个网格线并且不少于3行。

我的python ocde:

    #yList is a list of float numbers
    #xList is a list of float numbers

    rcParams['figure.figsize'] = 6, 6
    plt.scatter(xList, yList, s=3, c='g', alpha=0.5)
    plt.Figure(figsize=(1,1), facecolor='w')
    plt.ylim(0, max(yList))
    plt.xlim(0, max(xList))

    plt.grid()
    plt.show()

目前,每个网格单元都是直肠的。我需要每个细胞的正方形。

1 个答案:

答案 0 :(得分:0)

可以使用ax.set_x/yticks调整网格,然后ax.set_aspect调整比例。如果你正确地做到了(首先你要根据xmax和ymax之间的差异来校正比率,然后选择案例数量的比例),你将得到方格网格单元

import random
import matplotlib.pyplot as plt
xList = np.random.uniform(0,1,10)
yList = np.random.uniform(0,10,10)

fig = plt.figure()
ax = fig.gca()
plt.rcParams['figure.figsize'] = 6, 6
ax.scatter(xList, yList, s=3, c='g', alpha=0.5)
ax.set_ylim(0, max(yList))
ax.set_xlim(0, max(xList))

#Added code
n_x, ny = 3, 8
ax.set_xticks( np.linspace(*ax.get_xlim(), num=n_x+1) ) #Need 4 points to make 3 intervals
ax.set_yticks( np.linspace(*ax.get_ylim(), num=n_y+1) ) #Need 9 points to make 8 intervals

ax.set_aspect( ax.get_xlim()[1]/ax.get_ylim()[1] * n_y/n_x  ) 
# ax.get_xlim()[1]/ax.get_ylim()[1] correct difference between xmax and ymax, 
# n_y/n_x put the correct scale to get square grid cells

ax.grid()
fig.show()

enter image description here