标签: subplot

Matplotlib:在子图的网格中重新定位子图

我试图制作一个包含7个子图的情节.目前我正在绘制两个列,一个有四个图,另一个有三个,就像这样:在此输入图像描述

我正在按照以下方式构建这个情节:

    #! /usr/bin/env python
    import numpy as plotting
    import matplotlib
    from pylab import *
    x = np.random.rand(20)
    y = np.random.rand(20)
    fig = figure(figsize=(6.5,12))
    subplots_adjust(wspace=0.2,hspace=0.2)
    iplot = 420
    for i in range(7):
       iplot += 1
       ax = fig.add_subplot(iplot)
       ax.plot(x,y,'ko')
       ax.set_xlabel("x")
       ax.set_ylabel("y")
    savefig("subplots_example.png",bbox_inches='tight')
Run Code Online (Sandbox Code Playgroud)

但是,对于发布我认为这看起来有点难看 - 我想要做的是将最后一个子图移动到两列之间的中心.那么,调整最后一个子图的位置以使其居中的最佳方法是什么?即,在3X2网格中有前6个子图,下面的最后一个子图在两列之间居中.如果可能的话,我希望能够保持for循环,以便我可以简单地使用:

    if i == 6:
       # do something to reposition/centre this plot     
Run Code Online (Sandbox Code Playgroud)

谢谢,

亚历克斯

python customization matplotlib subplot

8
推荐指数
2
解决办法
9393
查看次数

使用子图时颜色条位置错误(matplotlib)

我想创建一个由九个子图组成的图形.我真的很讨厌我需要分别创建ax1到ax9的事实所以我创建了一个for循环来这样做.但是,当我想要包含一个颜色条时,颜色条位于最后一个子图的右侧.这也在下图中说明:

在此输入图像描述

出了什么问题,我该如何解决这个问题?

已使用以下代码生成图像:

import numpy
import layout
import matplotlib.pylab as plt

data = numpy.random.random((10, 10))

test = ["ax1", "ax2", "ax3", "ax4", "ax5", "ax6", "ax7", "ax8", "ax9"]

fig = plt.figure(1)

for idx in range(len(test)):
    vars()[test[idx]] = fig.add_subplot(3, 3, (idx + 1))

im = ax1.imshow(data)
plt.colorbar(im)

im2 = ax3.imshow(data)
plt.colorbar(im2)

plt.show()
Run Code Online (Sandbox Code Playgroud)

python plot matplotlib colorbar subplot

8
推荐指数
2
解决办法
7137
查看次数

子图用不同的colormaps matlab

我试图用两个不同的contourf子图来制作一个使用完全不同的colormap的图.但是,对于我目前拥有的代码(为其中一个子图创建自定义颜色图),子图使用相同的颜色图.任何想法如何解决这一问题?

h = figure;
subplot(2,1,1)
title('GEFS 20 Member Mean Vorticity');
axesm('eqdcylin','maplonlimit',[-180 179],'maplatlimit',[0 90]);
%eqdcylin
contourm(gLat, gLon, squeeze(meanhx(x,:,:))', 16,'Color',[0.05 0.05 0.05],'LineWidth',2);
hold on
contourfm(gLat, gLon, squeeze(vmeanx(x,:,:))', 30, 'LineStyle', 'none'); 
shading flat;
lm=worldlo('POline');
  for i=1:length(lm);
  lm(i).otherproperty = {'color','m','LineWidth',1.5};
  end
displaym(lm);
gridm on;
tightmap;
set(h, 'Position', [1 1 2200 1100]);
colormap(b2r(-5*10^-5, 5*10^-5));
freezeColors;
cbfreeze(colorbar)




%caxis([-5*10^-5 5*10^-5])

colorbar;


subplot(2,1,2)
title('GEFS 20 Member Vorticity Variance');
axesm('eqdcylin','maplonlimit',[-180 179],'maplatlimit',[0 90]);
%eqdcylin
contourm(gLat, gLon, squeeze(meanhx(x,:,:))', 16,'Color',[0.05 0.05 0.05],'LineWidth',2);
hold on
contourfm(gLat, gLon, squeeze(vvarx(x,:,:))', 30, 'LineStyle', 'none'); 
shading flat; …
Run Code Online (Sandbox Code Playgroud)

matlab subplot matlab-figure contourf

8
推荐指数
1
解决办法
3117
查看次数

Python - 使用matplotlib组织3个子图

我尝试为我的身材生成3个子图.它看起来很有效,但并不是完全一致的.如何在底部的数字和下面的数字之间有相同的宽度?

plt.close()
fig = plt.figure()

ax1 = plt.subplot(211)
ax1.plot(cycles,np.asarray(df_int),'wo',label='')
ax1.plot(cycles,np.asarray(df_proj),'k+',label='')
ax1.legend(loc=2)
#ax1.subplots_adjust(left=0.15)
ax1.set_ylim(0.001,0.004)

ax2 = plt.subplot(223)
i2=ax2.imshow(c,cmap=plt.cm.hot, vmin=-5, vmax=5);#plt.colorbar();plt.clim(-5,5)
cb2=plt.colorbar(i2,ax=ax2,ticks=[-5,0,5],fraction=0.046, pad=0.04,format='%.2f')
cb2.ax.tick_params(labelsize=12)



ax3 = plt.subplot(224)
i3=ax3.imshow(residue_proj,cmap=plt.cm.hot, vmin=-5, vmax=5);#plt.colorbar();plt.clim(-5,5);
cb3=plt.colorbar(i3,ax=ax3,ticks=[-5,0,5],fraction=0.046, pad=0.04,format='%.2f')
cb3.ax.tick_params(labelsize=12)

plt.savefig('test.png', dpi=500,  bbox_inches='tight', pad_inches=0.1)
#plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

python matplotlib subplot

8
推荐指数
2
解决办法
1万
查看次数

单个窗口中的多个数字

我想创建一个功能,在一个窗口中在屏幕上绘制一组图形.到现在为止我写这段代码:

import pylab as pl

def plot_figures(figures):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary

    """
    for title in figures:
        pl.figure()
        pl.imshow(figures[title])
        pl.gray()
        pl.title(title)
        pl.axis('off')
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但我想有选择在单个窗口中绘制所有数字.而这段代码没有.我读了一些关于subplot的东西,但看起来很棘手.

python image matplotlib subplot

7
推荐指数
1
解决办法
1万
查看次数

在2d子图上循环,好像它是1-D

我试图使用子图绘制许多数据,我没有遇到麻烦,但我想知道是否有一种方便的方法来做到这一点.

下面是示例代码.

import numpy as np    
import math 
import matplotlib.pyplot as plt

quantities=["sam_mvir","mvir","rvir","rs","vrms","vmax"
,"jx","jy","jz","spin","m200b","m200c","m500c","m2500c"
,"xoff","voff","btoc","ctoa","ax","ay","az"]

# len(quantities) = 21, just to make the second loop expression 
# shorter in this post.

ncol = 5
nrow = math.ceil(21 / ncol)

fig, axes = plt.subplots(nrows = nrow, ncols=ncol, figsize=(8,6))

for i in range(nrow):
    for j in range(((21-i*5)>5)*5 + ((21-i*5)<5)*(21%5)):
        axes[i, j].plot(tree[quantities[i*ncol + j]]) 
        axes[i, j].set_title(quantities[i*ncol + j])
Run Code Online (Sandbox Code Playgroud)

此代码循环遍历2D子阵列,并在第21个图中停止,留下4个面板.我的问题是,有没有内置的方法来完成这项任务?例如,制作2D子图阵列并将阵列"展平"为1D,然后在1D阵列上循环0到20.

第二个范围()中的表达式非常难看.我不认为我会使用这段代码.我认为琐碎的方法是计算图表的数量,如果计数> 21则中断.但我只是想知道是否有更好的(或奇特的)方式.

python matplotlib flatten subplot

7
推荐指数
2
解决办法
3210
查看次数

对于matplotlib子图,Axes.invert_axis()不能与sharey = True一起使用

我试图使用倒y轴制作4个子图(2x2),同时在子图之间共享y轴.这是我得到的:

import matplotlib.pyplot as plt
import numpy as np

fig,AX = plt.subplots(2, 2, sharex=True, sharey=True)

for ax in AX.flatten():
    ax.invert_yaxis()
    ax.plot(range(10), np.random.random(10))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

似乎ax.invert_axis()被忽略了sharey=True.如果我设置sharey=False我在所有子图中得到一个倒y轴但显然y轴不再在子图之间共享.我在这里做错了,这是一个错误,还是做这样的事情没有意义?

python matplotlib subplot

7
推荐指数
1
解决办法
7164
查看次数

如何使用pandas DataFrame绘图函数绘制每个子图的ylabel

默认情况下,使用subplots选项的pandas.DataFrame.plot()似乎不容易为每个子图绘制ylabel.我试图绘制一个pandas数据帧,在数据帧中每列有一个子图.到目前为止,代码不起作用:

fig = plt.figure(figsize=(10,10))
ax = plt.gca()
df.plot(y=vars, ax=ax, subplots=True, layout=(3,1), sharex=True, legend=False,)
ax.set_ylabel = ['y','x', 'z']
Run Code Online (Sandbox Code Playgroud)

但这并没有绘制任何标签.

python plot matplotlib pandas subplot

7
推荐指数
1
解决办法
4526
查看次数

对 matplotlib 中的不同子图使用相同的颜色条

我正在使用以下过程在子图中绘制不同的图形。

fig = figure(figsize=(10,11))
subplots_adjust(wspace=0.5,hspace=0.2)
iplot = 330
for i in range(9):
    iplot += 1
    ax = fig.add_subplot(iplot)
    ## Comparison Mreal - Real
    tmp = REAL[REAL.days==days[i]]
    tmp = tmp.score
    tmp = np.array(tmp)
    tmp = tmp.reshape(len(xv), len(br))
    im = plt.imshow(tmp, interpolation='nearest', cmap='gnuplot', vmin = 0, vmax = 1,  extent=[0.05,0.5,1,0.05],
              aspect=0.5)
    xtmp = [0.05, 0.2, 0.3, 0.4, 0.5]
    plt.xticks(xtmp)
    ytmp = [0.05, 0.2, 0.4, 0.6, 0.8, 1.0]
    plt.yticks(ytmp)
    ax.grid(False)
divider = make_axes_locatable(plt.gca())
cax = divider.append_axes("right", "5%", pad="3%")
plt.colorbar(im, cax=cax)
plt.tight_layout()
Run Code Online (Sandbox Code Playgroud)

这就是我得到的:

在此处输入图片说明

但是,我希望所有子图都具有相同的颜色条,例如在图的右侧。

python matplotlib colorbar subplot

7
推荐指数
1
解决办法
8573
查看次数

将函数中创建的图窗添加到另一个图窗的子图中

我创建了两个函数来绘制两个特定的图并返回各自的数字:

import matplotlib.pyplot as plt

x = range(1,100)
y = range(1,100)

def my_plot_1(x,y):
    fig = plt.plot(x,y)
    return fig

def my_plot_2(x,y):
    fig = plt.plot(x,y)
    return fig
Run Code Online (Sandbox Code Playgroud)

现在,在我的函数之外,我想创建一个带有两个子图的图形并将我的函数图形添加到其中。像这样的东西:

my_fig_1 = my_plot_1(x,y)
my_fig_2 = my_plot_2(x,y)

fig, fig_axes = plt.subplots(ncols=2, nrows=1)
fig_axes[0,0] = my_fig_1
fig_axes[0,1] = my_fig_2
Run Code Online (Sandbox Code Playgroud)

然而,仅仅将创建的图形分配给这个新图形是行不通的。该函数调用该图窗,但未在子图中分配该图窗。有没有办法将我的函数图放置在另一个图的子图中?

python graph matplotlib figure subplot

7
推荐指数
1
解决办法
5966
查看次数