web-dev-qa-db-ja.com

Matplotlibで描いた図形の大きさをどこかに変更しますか?

Matplotlibで描く図形の大きさをどうやって変更しますか?

1443
tatwright

figure はコールサインを教えてくれます:

from matplotlib.pyplot import figure
figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')

別のdpi引数を指定しない限り、figure(figsize=(1,1))は1インチx 1インチの画像を作成します。これは80 x 80ピクセルになります。

833

すでにフィギュアが作成されている場合は、すぐにこれを実行できます。

fig = matplotlib.pyplot.gcf()
fig.set_size_inches(18.5, 10.5)
fig.savefig('test2png.png', dpi=100)

サイズの変更を既存のguiウィンドウに伝播するには、forward=Trueを追加します。

fig.set_size_inches(18.5, 10.5, forward=True)
612
Pete

廃止予定のノート:
公式のMatplotlibガイド に従って、pylabモジュールの使用はもはや推奨されていません。 その他の答え で説明されているように、代わりにmatplotlib.pyplotモジュールを使用することを検討してください。

以下はうまくいくようです。

from pylab import rcParams
rcParams['figure.figsize'] = 5, 10

これにより、Figureの幅は5インチ、高さは10インチになります。 インチ

Figureクラスはこれを引数の一つのデフォルト値として使います。

298
tatwright

次のような簡単なコードを試してください。

from matplotlib import pyplot as plt
plt.figure(figsize=(1,1))
x = [1,2,3]
plt.plot(x, x)
plt.show()

プロットする前に、Figureのサイズを設定する必要があります。

203
iPAS

Plt.rcParamsを使う

Figure環境を使用せずにサイズを変更したい場合のためのこの回避策もあります。たとえば、 plt.plot() を使用している場合は、幅と高さを使ってTupleを設定できます。

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (20,3)

これは(例えばIPython Notebookを使って)インラインでプロットするときにとても便利です。 @asamaierが気づいたように、このステートメントをimportsステートメントの同じセルに入れない方が望ましいです。

Cmへの変換

figsizeタプルはインチを受け入れます、それであなたがそれをセンチメートルに設定したいのであれば2.54でそれらを割る必要があります この質問 を見てください。

200
G M

'matplotlib figure size'に対するGoogleの最初のリンクは AdjustingImageSizeページのGoogleキャッシュ )です。

これは上記のページのテストスクリプトです。同じ画像の異なるサイズのtest[1-3].pngファイルを作成します。

#!/usr/bin/env python
"""
This is a small demo file that helps teach how to adjust figure sizes
for matplotlib

"""

import matplotlib
print "using MPL version:", matplotlib.__version__
matplotlib.use("WXAgg") # do this before pylab so you don'tget the default back end.

import pylab
import numpy as np

# Generate and plot some simple data:
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)

pylab.plot(x,y)
F = pylab.gcf()

# Now check everything with the defaults:
DPI = F.get_dpi()
print "DPI:", DPI
DefaultSize = F.get_size_inches()
print "Default size in Inches", DefaultSize
print "Which should result in a %i x %i Image"%(DPI*DefaultSize[0], DPI*DefaultSize[1])
# the default is 100dpi for savefig:
F.savefig("test1.png")
# this gives me a 797 x 566 pixel image, which is about 100 DPI

# Now make the image twice as big, while keeping the fonts and all the
# same size
F.set_size_inches( (DefaultSize[0]*2, DefaultSize[1]*2) )
Size = F.get_size_inches()
print "Size in Inches", Size
F.savefig("test2.png")
# this results in a 1595x1132 image

# Now make the image twice as big, making all the fonts and lines
# bigger too.

F.set_size_inches( DefaultSize )# resetthe size
Size = F.get_size_inches()
print "Size in Inches", Size
F.savefig("test3.png", dpi = (200)) # change the dpi
# this also results in a 1595x1132 image, but the fonts are larger.

出力:

using MPL version: 0.98.1
DPI: 80
Default size in Inches [ 8.  6.]
Which should result in a 640 x 480 Image
Size in Inches [ 16.  12.]
Size in Inches [ 16.  12.]

2つのメモ:

  1. モジュールのコメントと実際の出力は異なります。

  2. この答え サイズの違いを見るために1つの画像ファイルに3つの画像すべてを簡単に組み合わせることができます。

68
jfs

Pandasでフィギュアサイズを変更する方法を探している場合は、次のようにします。

df['some_column'].plot(figsize=(10, 5))

dfはPandasデータフレームです。デフォルト設定を変更したい場合は、次のようにします。

import matplotlib

matplotlib.rc('figure', figsize=(10, 5))
51
Kris

matplotlib.figure.Figure )から簡単に使用できます。

fig.set_size_inches(width,height)

Matplotlib 2.0.0以降、キャンバスへの変更はforwardキーワード デフォルトはTrue として直ちに表示されます。

両方ではなく width または height だけを使用したい場合は、次のようにします。

fig.set_figwidth(val)またはfig.set_figheight(val)

これらはキャンバスを直ちに更新しますが、Matplotlib 2.2.0以降でのみです。

それ以前のバージョン

上記で指定されたものよりも古いバージョンでキャンバスをライブアップデートするには、forward=Trueを明示的に指定する必要があります。 set_figwidthset_figheight関数はMatplotlib 1.5.0より前のバージョンではforwardパラメータをサポートしていないことに注意してください。

31
River

fig = ...行をコメントアウトしてみてください

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

N = 50
x = np.random.Rand(N)
y = np.random.Rand(N)
area = np.pi * (15 * np.random.Rand(N))**2

fig = plt.figure(figsize=(18, 18))
plt.scatter(x, y, s=area, alpha=0.5)
plt.show()
26
Renaud

FigureのサイズをN倍にするには、pl.show()の直前にこれを挿入する必要があります。

N = 2
params = pl.gcf()
plSize = params.get_size_inches()
params.set_size_inches( (plSize[0]*N, plSize[1]*N) )

また、ipythonのノートブックでもうまくいきます。

14
psihodelia
import matplotlib.pyplot as plt
plt.figure(figsize=(20,10))
plt.plot(x,y) ## This is your plot
plt.show()

以下も使用できます。

fig, ax = plt.subplots(figsize=(20, 10))
12
amalik2205

これは私にはうまくいきます:

from matplotlib import pyplot as plt
F = gcf()
Size = F.get_size_inches()
F.set_size_inches(Size[0]*2, Size[1]*2, forward=True)#Set forward to True to resize window along with plot in figure.
plt.show() #or plt.imshow(z_array) if using an animation, where z_array is a matrix or numpy array

これも役立つかもしれません: http://matplotlib.1069221.n5.nabble.com/Resizing-figure-windows-td11424.html

9
Blairg23

Matplotlib できません はメートル法をネイティブに使用するため、センチメートルなどの適当な長さの単位で図形のサイズを指定する場合は、次のようにします( gns-ank ):

def cm2inch(*tupl):
    inch = 2.54
    if isinstance(tupl[0], Tuple):
        return Tuple(i/inch for i in tupl[0])
    else:
        return Tuple(i/inch for i in tupl)

それからあなたは使用することができます:

plt.figure(figsize=cm2inch(21, 29.7))
8

これはFigureが描かれた直後でもFigureのサイズを変更します(少なくともmattotlib 1.4.0でQt4Agg/TkAggを使う - ただしMacOSXは使わない)。

matplotlib.pyplot.get_current_fig_manager().resize(width_px, height_px)
7
wilywampa

Matplotlibでrc()関数を使用するためのもう1つのオプション(単位はインチ)

import matplotlib
matplotlib.rc('figure', figsize=[10,5])
2
Student222