Matplotlib提供了ValueError:当我再添加一个子批次时,图像大小像素太大

Matplotlib提供了ValueError:当我再添加一个子批次时,图像大小像素太大,matplotlib,subplot,Matplotlib,Subplot,今天,我几乎整天都在努力解决图像大小的问题,当我尝试使用matplotlib add_subplot函数将多个绘图合并为一个图形时,像素太大了 我可以单独绘制每个图,但当我将它们组合在一起时,我会遇到这个问题。 下面是复制此值错误的简化代码 from matplotlib import pyplot as plt import numpy as np import os def plot_in_subplots(): fig= plt.figure(figsize=(15, 10))

今天,我几乎整天都在努力解决图像大小的问题,当我尝试使用matplotlib add_subplot函数将多个绘图合并为一个图形时,像素太大了

我可以单独绘制每个图,但当我将它们组合在一起时,我会遇到这个问题。 下面是复制此值错误的简化代码

from matplotlib import  pyplot as plt
import numpy as np
import os

def plot_in_subplots():
    fig= plt.figure(figsize=(15, 10))

    axis1=fig.add_subplot(311)
    # Uncomment line below to replicate ValueError: Image size of 3719x61904113 pixels is too large. It must be less than 2^16 in each direction.
    # axis2=fig.add_subplot(312)

    plot_bar_plot_in_given_axis(axis1)
    # plot_in_given_axis(axis2)

    figFile = os.path.join('/Users/burcakotlu/Desktop/Test_subplot.png')
    fig.savefig(figFile, dpi=100, bbox_inches="tight")
    plt.cla()
    plt.close(fig)

def plot_in_given_axis(ax):
    xticklabels_list = ['a','b','c','d','e','f'] * 6
    rows=['row1']

    ax.set_xlim([0, 36])
    ax.set_xticklabels([])

    ax.tick_params(axis='x', which='minor', length=0, labelsize=35)
    ax.set_xticks(np.arange(0, 36, 1))
    ax.set_xticks(np.arange(0, 36, 1) + 0.5, minor=True)
    ax.set_xticklabels(xticklabels_list, minor=True)

    ax.xaxis.set_label_position('top')
    ax.xaxis.set_ticks_position('top')

    plt.tick_params(
        axis='x',  # changes apply to the x-axis
        which='major',  # both major and minor ticks are affected
        bottom=False,  # ticks along the bottom edge are off
        top=False)  # labels along the bottom edge are off

    ax.set_ylim([0, len(rows)])
    ax.set_yticklabels([])

    ax.tick_params(axis='y', which='minor', length=0, labelsize=40)

    ax.set_yticks(np.arange(0, len(rows), 1))
    ax.set_yticks(np.arange(0, len(rows), 1) + 0.5, minor=True)
    ax.set_yticklabels(rows, minor=True)  # fontsize

    plt.tick_params(
        axis='y',  # changes apply to the x-axis
        which='major',  # both major and minor ticks are affected
        left=False)  # labels along the bottom edge are off

    ax.grid(which='major', color='black', zorder=3)

def plot_bar_plot_in_given_axis(ax):
    x_axis_labels = ['a', 'b', 'c', 'd', 'e', 'f']
    real_values1 = [266655.0, 0.0, 14072.0, 4137.0, 6752.5, 0.0]
    real_values2 = [273342.5, 0.0, 12598.5, 4240.0, 7425.5, 0.0]
    unreal_values1 = [326188.16, 0.0, 15828.42, 4666.825000000001, 8109.87, 0.0]
    unreal_values2 = [344462.07, 0.0, 16368.664999999999, 5180.2, 8721.64, 0.0]
    q_values = [2.5309603790195403e-28, 1.0, 1.8194829804783173e-33, 0.003603381046779825, 1.0, 1.0]
    name1 = 'X'
    name2 = 'Y'
    color1 = 'r'
    color2 = 'b'
    width = 0.1

    ind = np.arange(len(x_axis_labels))
    legend=None
    rects3=None
    rects4=None

    rects1 = ax.bar(ind, real_values1, width=width, edgecolor='black', color=color1)
    rects2 = ax.bar(ind + width, real_values2, width=width, edgecolor='black', color=color2)

    if ((unreal_values1 is not None) and unreal_values1):
        rects3 = ax.bar(ind+ 2*width, unreal_values1, width=width, edgecolor='black', color=color1, hatch = 'X')
    if ((unreal_values2 is not None) and unreal_values2):
        rects4 = ax.bar(ind +3*width, unreal_values2, width=width, edgecolor='black', color=color2, hatch = 'X')

    ax.tick_params(axis='x', labelsize=35)
    ax.tick_params(axis='y', labelsize=35)

    locs, labels = plt.yticks()
    ax.set_ylim(0, locs[-1] + 5000)
    ax.set_title('%s vs. %s' %(name1,name2), fontsize=20,fontweight='bold')
    ax.set_xticklabels(x_axis_labels, fontsize=35)
    plt.ylabel('Y axis label', fontsize=35, fontweight='normal')

    ax.set_xticks(ind + (3 * width) / 2)
    realStrand1Name = 'Real %s' % (name1)
    realStrand2Name = 'Real %s' % (name2)
    simulationsStrand1Name = 'Unreal %s' % (name1)
    simulationsStrand2Name = 'Unreal %s' % (name2)
    if ((rects1 is not None) and (rects2 is not None) and (rects3 is not None) and (rects4 is not None)):
        if ((len(rects1) > 0) and (len(rects2) > 0) and (len(rects3) > 0) and (len(rects4) > 0)):
            legend = ax.legend((rects1[0], rects2[0], rects3[0], rects4[0]),
                               (realStrand1Name, realStrand2Name, simulationsStrand1Name, simulationsStrand2Name),prop={'size': 25}, ncol=1, loc='best')

    ax.set_facecolor('white')
    ax.spines["bottom"].set_color('black')
    ax.spines["left"].set_color('black')
    ax.spines["top"].set_color('black')
    ax.spines["right"].set_color('black')

    if (legend is not None):
        frame = legend.get_frame()
        frame.set_facecolor('white')
        frame.set_edgecolor('black')

    if q_values is not None:
        for q_value, rect1, rect2 in zip(q_values,rects1,rects2):
            # Get X and Y placement of label from rect.
            y_value = max(rect1.get_height(),rect2.get_height())
            x_value = rect1.get_x() + rect1.get_width()

            space = 3
            va = 'bottom'
            if y_value < 0:
                space *= -1
                va = 'top'

            if ((q_value is not None) and (q_value)<=0.05):
                plt.annotate(
                    '***',  # Use `label` as label
                    (x_value, y_value),  # Place label at end of the bar
                    xytext=(0, space),  # Vertically shift label by `space`
                    textcoords="offset points",  # Interpret `xytext` as offset in points
                    ha='center',  # Horizontally center label
                    va=va,
                    fontsize=20) # Vertically align label differently for

plot_in_subplots()
从matplotlib导入pyplot作为plt
将numpy作为np导入
导入操作系统
def plot_在_子图()中:
图=plt.图(图尺寸=(15,10))
axis1=图添加_子批次(311)
#取消下面的行注释以复制ValueError:3719x61904113像素的图像大小太大。在每个方向上必须小于2^16。
#axis2=图添加_子批次(312)
在给定轴(轴1)中绘图
#在给定轴(轴2)中绘制
figFile=os.path.join('/Users/burcakotlu/Desktop/Test_subplot.png'))
图savefig(figFile,dpi=100,bbox_英寸=“紧密”)
plt.cla()
plt.关闭(图)
给定轴(ax)中的def绘图:
xticklabels_list=['a'、'b'、'c'、'd'、'e'、'f']*6
行=['row1']
ax.set_xlim([0,36])
ax.setxticklabels([])
ax.tick_参数(axis='x',which='minor',length=0,labelsize=35)
ax.set_xticks(np.arange(0,36,1))
ax.set_xticks(np.arange(0,36,1)+0.5,minor=True)
ax.set_xticklabels(xticklabels_列表,minor=True)
ax.xaxis.set_label_位置('top'))
ax.xaxis.set_ticks_位置('top'))
plt.tick_参数(
axis='x',#更改适用于x轴
哪个=‘主要’,主要和次要蜱虫都会受到影响
底部=假,#沿底部边缘的勾号已禁用
顶部=假)#沿底部边缘的标签已关闭
ax.set_ylim([0,len(行)])
ax.设置标签([])
ax.勾选参数(轴为y',其中为次轴,长度为0,标签大小为40)
ax.set_yticks(np.arange(0,len(行),1))
ax.set_yticks(np.arange(0,len(行),1)+0.5,minor=True)
ax.set#yticklabels(行,次=真)#fontsize
plt.tick_参数(
axis='y',#更改适用于x轴
哪个=‘主要’,主要和次要蜱虫都会受到影响
左=假)#沿底部边缘的标签已关闭
ax.grid(哪个='major',color='black',zorder=3)
给定轴(ax)中的def绘图条绘图:
x_轴_标签=['a'、'b'、'c'、'd'、'e'、'f']
实际值1=[266655.0,0.0,14072.0,4137.0,6752.5,0.0]
实际_值2=[273342.5,0.0,12598.54240.0,7425.5,0.0]
非真实值1=[326188.16,0.0,15828.42,4666.825000000001,8109.87,0.0]
非真实值2=[344462.07,0.0,16368.66499999995180.28721.64,0.0]
q_值=[2.5309603790195403e-28,1.0,1.8194829804783173e-33,0.003603381046779825,1.0,1.0]
name1='X'
名称2='Y'
color1='r'
color2='b'
宽度=0.1
ind=np.arange(len(x_轴标签))
图例=无
rects3=无
rects4=无
rects1=最大条形(ind,实际值1,宽度=宽度,边颜色=黑色,颜色=颜色1)
rects2=最大条形(ind+宽度,实数值2,宽度=宽度,边颜色=黑色,颜色=颜色2)
如果((非真实值1不是无)和非真实值1):
rects3=ax.bar(ind+2*宽度,非真实值1,宽度=宽度,edgecolor='black',color=color1,hatch='X')
如果((非真实值2不是无)和非真实值2):
rects4=ax.bar(ind+3*width,unreal_值2,width=width,edgecolor='black',color=color2,hatch='X')
ax.勾选参数(轴=x',标签大小=35)
ax.勾选参数(轴=y',标签大小=35)
locs,labels=plt.yticks()
最大设定值(0,位置[-1]+5000)
ax.set_title(“%s vs.%s%”(name1,name2),fontsize=20,fontwweight='bold')
ax.设置x轴标签(x轴标签,fontsize=35)
plt.ylabel('Y轴标签',fontsize=35,fontweight='normal')
最大设置宽度(ind+(3*宽度)/2)
RealStrandName='Real%s'(名称1)
realStrand2Name='Real%s'(名称2)
SimulationStrandName='不真实的%s'(名称1)
SimulationStrand2Name=“不真实的%s%”(名称2)
如果((rects1不是无)和(rects2不是无)以及(rects3不是无)和(rects4不是无)):
如果((len(rects1)>0)和(len(rects2)>0)和(len(rects3)>0)和(len(rects4)>0)):
legend=ax.legend((rects1[0]、rects2[0]、rects3[0]、rects4[0]),
(RealStrandName,RealStrandName,SimulationStrandName,SimulationStrandName),prop={'size':25},ncol=1,loc='best')
ax.set_facecolor(“白色”)
斧头刺[“底部”]。设置颜色(“黑色”)
斧头刺[“左”]。设置颜色(“黑色”)
斧头刺[“顶部”]。设置颜色(“黑色”)
斧头刺[“右”]。设置颜色(“黑色”)
如果(图例不是无):
frame=legend.get_frame()
frame.set_facecolor(“白色”)
框架设置颜色(“黑色”)
如果q_值不是无:
对于zip中的q_值、rect1、rect2(q_值、rects1、rects2):
#从rect获取标签的X和Y位置。
y_值=最大值(rect1.get_height(),rect2.get_height())
x_值=rect1.get_x()+rect1.get_宽度()
空间=3
va=‘底部’
如果y_值<0:
空格*=-1
va=‘顶级’

如果((q_值不是None)和(q_值)我已经升级到Matplotlib 3.4.2。 我将plt.xxx改为ax.xxx(面向对象)并使用gridspec,我就快到了。谢谢

from matplotlib import  pyplot as plt
from matplotlib import gridspec
import numpy as np
import os

def plot_in_subplots():
    fig= plt.figure(figsize=(30, 10))


    gs = gridspec.GridSpec(10, 4, width_ratios=[1,1,1,1], height_ratios=[1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
    axis1 = plt.subplot(gs[0:7, 1:3])
    axis2 = plt.subplot(gs[9, :])
    # bottom_left_axis = plt.subplot(gs[-1,0])
    # bottom_right_axis = plt.subplot(gs[-1,-1])

    # axis1=fig.add_subplot(211)
    # axis2=fig.add_subplot(212)

    plot_bar_plot_in_given_axis(axis1)
    plot_in_given_axis(axis2)

    figFile = os.path.join('/Users/burcakotlu/Desktop/Test_subplot.png')
    fig.savefig(figFile, dpi=100, bbox_inches="tight")
    plt.cla()
    plt.close(fig)

def plot_in_given_axis(ax):
    xticklabels_list = ['a','b','c','d','e','f'] * 6
    rows=['row1']

    ax.set_xlim([0, 36])
    ax.set_xticklabels([])

    ax.tick_params(axis='x', which='minor', length=0, labelsize=35)
    ax.set_xticks(np.arange(0, 36, 1))
    ax.set_xticks(np.arange(0, 36, 1) + 0.5, minor=True)
    ax.set_xticklabels(xticklabels_list, minor=True)

    ax.xaxis.set_label_position('top')
    ax.xaxis.set_ticks_position('top')

    ax.tick_params(
        axis='x',  # changes apply to the x-axis
        which='major',  # both major and minor ticks are affected
        bottom=False,  # ticks along the bottom edge are off
        top=False)  # labels along the bottom edge are off

    ax.set_ylim([0, len(rows)])
    ax.set_yticklabels([])

    ax.tick_params(axis='y', which='minor', length=0, labelsize=40)

    ax.set_yticks(np.arange(0, len(rows), 1))
    ax.set_yticks(np.arange(0, len(rows), 1) + 0.5, minor=True)
    ax.set_yticklabels(rows, minor=True)  # fontsize

    ax.tick_params(
        axis='y',  # changes apply to the x-axis
        which='major',  # both major and minor ticks are affected
        left=False)  # labels along the bottom edge are off

    ax.grid(which='major', color='black', zorder=3)

def plot_bar_plot_in_given_axis(ax):
    x_axis_labels = ['a', 'b', 'c', 'd', 'e', 'f']
    real_values1 = [266655.0, 0.0, 14072.0, 4137.0, 6752.5, 0.0]
    real_values2 = [273342.5, 0.0, 12598.5, 4240.0, 7425.5, 0.0]
    unreal_values1 = [326188.16, 0.0, 15828.42, 4666.825000000001, 8109.87, 0.0]
    unreal_values2 = [344462.07, 0.0, 16368.664999999999, 5180.2, 8721.64, 0.0]
    q_values = [2.5309603790195403e-28, 1.0, 1.8194829804783173e-33, 0.003603381046779825, 1.0, 1.0]
    name1 = 'X'
    name2 = 'Y'
    color1 = 'r'
    color2 = 'b'
    width = 0.1

    ind = np.arange(len(x_axis_labels))
    legend=None
    rects3=None
    rects4=None

    rects1 = ax.bar(ind, real_values1, width=width, edgecolor='black', color=color1)
    rects2 = ax.bar(ind + width, real_values2, width=width, edgecolor='black', color=color2)

    if ((unreal_values1 is not None) and unreal_values1):
        rects3 = ax.bar(ind+ 2*width, unreal_values1, width=width, edgecolor='black', color=color1, hatch = 'X')
    if ((unreal_values2 is not None) and unreal_values2):
        rects4 = ax.bar(ind +3*width, unreal_values2, width=width, edgecolor='black', color=color2, hatch = 'X')

    ax.tick_params(axis='x', labelsize=35)
    ax.tick_params(axis='y', labelsize=35)

    locs=ax.get_yticks()
    ax.set_ylim(0, locs[-1] + 5000)
    ax.set_title('%s vs. %s' %(name1,name2), fontsize=20,fontweight='bold')
    ax.set_xticklabels(x_axis_labels, fontsize=35)
    ax.set_ylabel('Y axis label', fontsize=35, fontweight='normal')

    ax.set_xticks(ind + (3 * width) / 2)
    realStrand1Name = 'Real %s' % (name1)
    realStrand2Name = 'Real %s' % (name2)
    simulationsStrand1Name = 'Unreal %s' % (name1)
    simulationsStrand2Name = 'Unreal %s' % (name2)
    if ((rects1 is not None) and (rects2 is not None) and (rects3 is not None) and (rects4 is not None)):
        if ((len(rects1) > 0) and (len(rects2) > 0) and (len(rects3) > 0) and (len(rects4) > 0)):
            legend = ax.legend((rects1[0], rects2[0], rects3[0], rects4[0]),
                               (realStrand1Name, realStrand2Name, simulationsStrand1Name, simulationsStrand2Name),prop={'size': 25}, ncol=1, loc='best')

    ax.set_facecolor('white')
    ax.spines["bottom"].set_color('black')
    ax.spines["left"].set_color('black')
    ax.spines["top"].set_color('black')
    ax.spines["right"].set_color('black')

    if (legend is not None):
        frame = legend.get_frame()
        frame.set_facecolor('white')
        frame.set_edgecolor('black')

    if q_values is not None:
        for q_value, rect1, rect2 in zip(q_values,rects1,rects2):
            # Get X and Y placement of label from rect.
            y_value = max(rect1.get_height(),rect2.get_height())
            x_value = rect1.get_x() + rect1.get_width()

            space = 3
            va = 'bottom'
            if y_value < 0:
                space *= -1
                va = 'top'

            if ((q_value is not None) and (q_value)<=0.05):
                ax.annotate(
                    '***',  # Use `label` as label
                    (x_value, y_value),  # Place label at end of the bar
                    xytext=(0, space),  # Vertically shift label by `space`
                    textcoords="offset points",  # Interpret `xytext` as offset in points
                    ha='center',  # Horizontally center label
                    va=va,
                    fontsize=20,
                transform=ax.transAxes) # Vertically align label differently for

plot_in_subplots()
从matplotlib导入pyplot作为plt
从matplotlib导入gridspec
将numpy作为np导入
导入操作系统
def plot_在_子图()中:
图=plt.图(图尺寸=(30,10))
gs=gridspec.gridspec(10,4,宽度比=[1,1,1,1],高度比=[1,1,1,1,1,1,1])
axis1=plt.子批次(gs[0:7,1:3])
axis2=plt.子批次(gs[9,:])
#底部\左\轴=plt.子批次(gs[-1,0])
#底部\右\轴=plt.子批次(gs[-1,-1])
#axis1=图添加_子批次(211)
#axis2=图add_子批次(212)
在给定轴(轴1)中绘图
在给定轴(轴2)中绘制
figFile=os.path.join('/Users/burcakotlu/Desktop/Test_subplot.png'))
无花果