如何制作 matplotlib 散点图正方形?
How do I make a matplotlib scatter plot square?
在 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 并使绘图呈正方形?
你可以这样做:
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)
设置图中尺寸:
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='--')
在 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 并使绘图呈正方形?
你可以这样做:
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)
设置图中尺寸:
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='--')