【发布时间】:2017-03-01 21:17:06
【问题描述】:
我在使用 Python 中的 matplotlib 尝试并排创建两个图时遇到问题。我设法让它们彼此相邻,但我需要它们具有完全相同的大小:右侧的每个点都应该很容易用肉眼映射到左侧的位置。 相反,我的右侧(散点图)有一些边距,使其看起来比左侧略小(热图)。
我生成热图的方式是:
def plot_map(matrix):
# Plot it out
#fig, ax = plt.subplots()
fig = plt.figure()
ax = plt.subplot(1,2,1)
c = m.colors.ColorConverter().to_rgb
cm = make_colormap([(0,1,0), (1,1,0), 0.1, (1,1,0), (1,0.5,0), 0.66, (1,0.5,0),(1,0,0)])
heatmap = ax.pcolor(matrix, cmap=cm)
# Format
fig = plt.gcf()
fig.set_size_inches(20, 20)
plt.gca().set_aspect('equal')
# turn off the frame
ax.set_frame_on(False)
# put the major ticks at the middle of each cell
ax.set_yticks(np.arange(matrix.shape[0]) + 0.5, minor=False)
ax.set_xticks(np.arange(matrix.shape[1]) + 0.5, minor=False)
# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()
# note I could have used matrix.columns but made "labels" instead
ax.set_xticklabels(range(0,matrix.shape[0]), minor=False)
ax.set_yticklabels(range(0,matrix.shape[1]), minor=False)
ax.grid(False)
# Turn off all the ticks
ax = plt.gca()
for t in ax.xaxis.get_major_ticks():
t.tick1On = False
t.tick2On = False
for t in ax.yaxis.get_major_ticks():
t.tick1On = False
t.tick2On = False
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(heatmap,cax=cax)
return (fig,ax)
然后将斧头传递给另一个函数以在地图上绘制小蓝线:
def plot_chosen(edges,endnodes,side,ax):
for e in edges:
u = endnodes[e - 1][0]
v = endnodes[e - 1][1]
xu, yu = get_center(u,side)
xv, yv = get_center(v,side)
ax.plot([xu+0.5, xv+0.5], [yu+0.5, yv+0.5], 'k-', lw=4, color='blue',alpha=0.5)
最后,我像这样绘制散点图
def plot_satter(edges,endnodes,side,xs,ys,data):
plt.margins(0)
ax = plt.subplot(1, 2, 2)
# Format
fig = plt.gcf()
fig.set_size_inches(20, 20)
plt.gca().set_aspect('equal')
# turn off the frame
ax.set_frame_on(False)
# put the major ticks at the middle of each cell
ax.set_yticks(np.arange(side) + 0.5, minor=False)
ax.set_xticks(np.arange(side) + 0.5, minor=False)
# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()
ax.set_xmargin(0)
ax.set_ymargin(0)
# note I could have used matrix.columns but made "labels" instead
ax.set_xticklabels(range(0,side), minor=False)
ax.set_yticklabels(range(0,side), minor=False)
ax.grid(False)
# Turn off all the ticks
ax = plt.gca()
for t in ax.xaxis.get_major_ticks():
t.tick1On = False
t.tick2On = False
for t in ax.yaxis.get_major_ticks():
t.tick1On = False
t.tick2On = False
cm = make_colormap([(0,0,1), (0,1,1), 0.1, (0,1,1), (1,1,0), 0.66, (1,1,0),(1,0,0)])
resmap = plt.scatter(xs,ys, c=data,cmap=cm,edgecolors='none',alpha=0.5,s=data)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(resmap,cax=cax)
但我找不到使散点图与热图一样大的方法。实际上,它应该和它的颜色条一样大,但这也不起作用......这让我觉得散布点周围有一些余量......
另外,有没有办法让整个 PNG 文件不那么方正?会不会是一个长方形?
谢谢!
【问题讨论】:
-
代码太多了……能不能尽量去掉,做成一个可运行的MCVE-example?
标签: python matplotlib plot scatter-plot subplot