如何使用子图更改图形大小?
- 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.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);
但是,如果希望绘制不同大小的子图,一种方法是使用,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
最后,如果需要制作自定义大小的子图,一种方法是将(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
扫码咨询,免费领取项目管理大礼包!