如何使用子图更改图形大小?

2025-02-28 08:23:00
admin
原创
77
摘要:问题描述:我如何增加此图形的尺寸?这什么也不做:f.figsize(15, 15) 来自链接的示例代码:import matplotlib.pyplot as plt import numpy as np # Simple data to display in various forms x = np.li...

问题描述:

我如何增加此图形的尺寸?

这什么也不做:

f.figsize(15, 15)

来自链接的示例代码:

import matplotlib.pyplot as plt
import numpy as np

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

plt.close('all')

# Just a figure and one subplot
f, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')

# Two subplots, the axes array is 1-d
f, axarr = plt.subplots(2, sharex=True)
axarr[0].plot(x, y)
axarr[0].set_title('Sharing X axis')
axarr[1].scatter(x, y)

# Two subplots, unpack the axes array immediately
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)

# Three subplots sharing both x/y axes
f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing both axes')
ax2.scatter(x, y)
ax3.scatter(x, 2 * y ** 2 - 1, color='r')
# Fine-tune figure; make subplots close to each other and hide x ticks for
# all but bottom plot.
f.subplots_adjust(hspace=0)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)

# row and column sharing
f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row')
ax1.plot(x, y)
ax1.set_title('Sharing x per column, y per row')
ax2.scatter(x, y)
ax3.scatter(x, 2 * y ** 2 - 1, color='r')
ax4.plot(x, 2 * y ** 2 - 1, color='r')

# Four axes, returned as a 2-d array
f, axarr = plt.subplots(2, 2)
axarr[0, 0].plot(x, y)
axarr[0, 0].set_title('Axis [0,0]')
axarr[0, 1].scatter(x, y)
axarr[0, 1].set_title('Axis [0,1]')
axarr[1, 0].plot(x, y ** 2)
axarr[1, 0].set_title('Axis [1,0]')
axarr[1, 1].scatter(x, y ** 2)
axarr[1, 1].set_title('Axis [1,1]')
# Fine-tune figure; hide x ticks for top plots and y ticks for right plots
plt.setp([a.get_xticklabels() for a in axarr[0, :]], visible=False)
plt.setp([a.get_yticklabels() for a in axarr[:, 1]], visible=False)

# Four polar axes
f, axarr = plt.subplots(2, 2, subplot_kw=dict(projection='polar'))
axarr[0, 0].plot(x, y)
axarr[0, 0].set_title('Axis [0,0]')
axarr[0, 1].scatter(x, y)
axarr[0, 1].set_title('Axis [0,1]')
axarr[1, 0].plot(x, y ** 2)
axarr[1, 0].set_title('Axis [1,0]')
axarr[1, 1].scatter(x, y ** 2)
axarr[1, 1].set_title('Axis [1,1]')
# Fine-tune figure; make subplots farther from each other.
f.subplots_adjust(hspace=0.3)

plt.show()

解决方案 1:

对返回的对象使用.set_figwidth和,或用 来设置两者。.set_figheight`matplotlib.figure.Figureplt.subplots()f.set_size_inches(w, h)`

f.set_figheight(15)
f.set_figwidth(15)

注意:与 不同,其中测量单位在函数名称中明确提及,但和set_size_inches()并非如此,它们也使用英寸。此信息由函数文档提供。set_figwidth()`set_figheight()`

或者,当使用.subplots()创建新图形时,指定figsize=

f, axs = plt.subplots(2, 2, figsize=(15, 15))

.subplots接受**fig_kw,并将其传递给pyplot.figure,并且 在哪里figsize可以找到 。

设置图形的大小可能会触发ValueError异常:

Image size of 240000x180000 pixels is too large. It must be less than 2^16 in each direction

这是使用这些set_fig*()函数时的一个常见问题,因为它们假设它们以像素而不是英寸为单位工作(显然 240000*180000 英寸太多了)。

解决方案 2:

除了前面的答案之外,还有一个选项可以通过以下方式单独设置图形的大小和图形内子图的大小gridspec_kw

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

#generate random data
x,y=range(100), range(10)
z=np.random.random((len(x),len(y)))
Y=[z[i].sum() for i in range(len(x))]
z=pd.DataFrame(z).unstack().reset_index()

#Plot data
fig, axs = plt.subplots(2,1,figsize=(16,9), gridspec_kw={'height_ratios': [1, 2]})
axs[0].plot(Y)
axs[1].scatter(z['level_1'], z['level_0'],c=z[0])

结果如下:
在此处输入图片描述

解决方案 3:

figure()或者,使用参数创建一个对象figsize,然后用它来add_subplot添加子图。例如

import matplotlib.pyplot as plt
import numpy as np

f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')

简单示例

这种方法的好处是语法更接近于调用subplot()而不是subplots()。例如,subplots 似乎不支持使用GridSpec来控制 subplots 的间距,但 和 都subplot()支持add_subplot()

解决方案 4:

您可以使用它plt.figure(figsize = (16,8))来更改单个图和最多两个子图的图形大小。(figsize 中的参数可以修改图形大小)

plt.subplots(2,2,figsize=(10,10))您可以在创建子图时使用它来更改更多子图的图形大小。

解决方案 5:

对于绘图subplots来说,for loop有时很有用:绘制来自(二维)matplotlib直方图的多个子图的示例代码。multivariate numpy array

plt.figure(figsize=(16, 8)) 
for i in range(1, 7):
    plt.subplot(2, 3, i)
    plt.title('Histogram of {}'.format(str(i)))
    plt.hist(x[:,i-1], bins=60)

解决方案 6:

gridspec_kw从 matplotlib 3.6.0 开始,height_ratios/width_ratios可以作为 kwargs 传递,而不是 via plt.subplots。因此可以按如下方式设置相对高度。

import matplotlib.pyplot as plt
import random
data = random.sample(range(100), k=100)

fig, axs = plt.subplots(2, figsize=(6,4), height_ratios=[1, 2])
#                                         ^^^^^^^^^  <---- here
axs[0].plot(data)
axs[1].scatter(range(100), data, s=10);

结果1


但是,如果希望绘制不同大小的子图,一种方法是使用,matplotlib.gridspec.GridSpec但更简单的方法是将适当的位置传递给add_subplot()调用。在下面的例子中,首先,绘制 2x1 布局中的第一个子图。然后,初始化 2x2 布局,但绘制其第三个子图(此布局中前两个子图的空间已被顶部图占用),而不是绘制 2x1 布局的第二个子图。

fig = plt.figure(figsize=(6, 4))

ax1 = fig.add_subplot(2, 1, 1)      # initialize the top Axes
ax1.plot(data)                      # plot the top graph

ax2 = fig.add_subplot(2, 2, 3)      # initialize the bottom left Axes
ax2.scatter(range(100), data, s=10) # plot the bottom left graph

ax3 = fig.add_subplot(2, 2, 4)      # initialize the bottom right Axes
ax3.plot(data)                      # plot the bottom right graph

结果2


最后,如果需要制作自定义大小的子图,一种方法是将(left, bottom, width, height)信息传递给add_axes()图形对象上的调用。

fig = plt.figure(figsize=(6,4))
ax1 = fig.add_axes([0.05, 0.6, 0.9, 0.25])  # add the top Axes
ax1.plot(data)                              # plot in the top Axes
ax2 = fig.add_axes([0.25, 0, 0.5, 0.5])     # add the bottom Axes
ax2.scatter(range(100), data, s=10);        # plot in the bottom Axes

结果3

相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   2974  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1836  
  PLM(产品生命周期管理)系统在企业的产品研发、生产与管理过程中扮演着至关重要的角色。然而,在实际运行中,资源冲突是经常会遇到的难题。资源冲突可能导致项目进度延迟、成本增加以及产品质量下降等一系列问题,严重影响企业的效益与竞争力。因此,如何有效应对PLM系统中的资源冲突,成为众多企业关注的焦点。接下来,我们将详细探讨5...
plm项目管理系统   47  
  敏捷项目管理与产品生命周期管理(PLM)的融合,正成为企业在复杂多变的市场环境中提升研发效率、增强竞争力的关键举措。随着技术的飞速发展和市场需求的快速更迭,传统的研发流程面临着诸多挑战,而将敏捷项目管理理念融入PLM,有望在2025年实现研发流程的深度优化,为企业创造更大的价值。理解敏捷项目管理与PLM的核心概念敏捷项...
plm项目   47  
  模块化设计在现代产品开发中扮演着至关重要的角色,它能够提升产品开发效率、降低成本、增强产品的可维护性与可扩展性。而产品生命周期管理(PLM)系统作为整合产品全生命周期信息的关键平台,对模块化设计有着强大的支持能力。随着技术的不断发展,到 2025 年,PLM 系统在支持模块化设计方面将有一系列令人瞩目的技术实践。数字化...
plm软件   48  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用