标签归档:matplotlib

在matplotlib中设置y轴限制

问题:在matplotlib中设置y轴限制

我需要在matplotlib上设置y轴限制的帮助。这是我尝试失败的代码。

import matplotlib.pyplot as plt

plt.figure(1, figsize = (8.5,11))
plt.suptitle('plot title')
ax = []
aPlot = plt.subplot(321, axisbg = 'w', title = "Year 1")
ax.append(aPlot)
plt.plot(paramValues,plotDataPrice[0], color = '#340B8C', 
     marker = 'o', ms = 5, mfc = '#EB1717')
plt.xticks(paramValues)
plt.ylabel('Average Price')
plt.xlabel('Mark-up')
plt.grid(True)
plt.ylim((25,250))

使用此图的数据,我得到的Y轴限制为20和200。但是,我希望限制为20和250。

I need help with setting the limits of y-axis on matplotlib. Here is the code that I tried, unsuccessfully.

import matplotlib.pyplot as plt

plt.figure(1, figsize = (8.5,11))
plt.suptitle('plot title')
ax = []
aPlot = plt.subplot(321, axisbg = 'w', title = "Year 1")
ax.append(aPlot)
plt.plot(paramValues,plotDataPrice[0], color = '#340B8C', 
     marker = 'o', ms = 5, mfc = '#EB1717')
plt.xticks(paramValues)
plt.ylabel('Average Price')
plt.xlabel('Mark-up')
plt.grid(True)
plt.ylim((25,250))

With the data I have for this plot, I get y-axis limits of 20 and 200. However, I want the limits 20 and 250.


回答 0

尝试这个 。也适用于子图。

axes = plt.gca()
axes.set_xlim([xmin,xmax])
axes.set_ylim([ymin,ymax])

Try this . Works for subplots too .

axes = plt.gca()
axes.set_xlim([xmin,xmax])
axes.set_ylim([ymin,ymax])

回答 1

您的代码也对我有用。但是,另一种解决方法是获取图的轴,然后仅更改y值:

x1,x2,y1,y2 = plt.axis()
plt.axis((x1,x2,25,250))

Your code works also for me. However, another workaround can be to get the plot’s axis and then change only the y-values:

x1,x2,y1,y2 = plt.axis()
plt.axis((x1,x2,25,250))


回答 2

您可以做的一件事是使用matplotlib.pyplot.axis自行设置轴范围。

matplotlib.pyplot.axis

from matplotlib import pyplot as plt
plt.axis([0, 10, 0, 20])

0,10用于x轴范围。0,20是y轴范围。

或者您也可以使用matplotlib.pyplot.xlim或matplotlib.pyplot.ylim

matplotlib.pyplot.ylim

plt.ylim(-2, 2)
plt.xlim(0,10)

One thing you can do is to set your axis range by yourself by using matplotlib.pyplot.axis.

matplotlib.pyplot.axis

from matplotlib import pyplot as plt
plt.axis([0, 10, 0, 20])

0,10 is for x axis range. 0,20 is for y axis range.

or you can also use matplotlib.pyplot.xlim or matplotlib.pyplot.ylim

matplotlib.pyplot.ylim

plt.ylim(-2, 2)
plt.xlim(0,10)

回答 3

您可以从中实例化对象matplotlib.pyplot.axes并对其进行调用set_ylim()。就像这样:

import matplotlib.pyplot as plt
axes = plt.axes()
axes.set_ylim([0, 1])

You can instantiate an object from matplotlib.pyplot.axes and call the set_ylim() on it. It would be something like this:

import matplotlib.pyplot as plt
axes = plt.axes()
axes.set_ylim([0, 1])

回答 4

这至少在matplotlib 2.2.2版中有效:

plt.axis([None, None, 0, 100])

大概这是设置例如xmin和ymax等的好方法。

This worked at least in matplotlib version 2.2.2:

plt.axis([None, None, 0, 100])

Probably this is a nice way to set up for example xmin and ymax only, etc.


回答 5

要添加到@Hima的答案中,如果要修改当前的x或y限制,可以使用以下内容。

import numpy as np # you probably alredy do this so no extra overhead
fig, axes = plt.subplot()
axes.plot(data[:,0], data[:,1])
xlim = axes.get_xlim()
# example of how to zoomout by a factor of 0.1
factor = 0.1 
new_xlim = (xlim[0] + xlim[1])/2 + np.array((-0.5, 0.5)) * (xlim[1] - xlim[0]) * (1 + factor) 
axes.set_xlim(new_xlim)

当我想从默认绘图设置中缩小或放大一点时,我发现这特别有用。

To add to @Hima’s answer, if you want to modify a current x or y limit you could use the following.

import numpy as np # you probably alredy do this so no extra overhead
fig, axes = plt.subplot()
axes.plot(data[:,0], data[:,1])
xlim = axes.get_xlim()
# example of how to zoomout by a factor of 0.1
factor = 0.1 
new_xlim = (xlim[0] + xlim[1])/2 + np.array((-0.5, 0.5)) * (xlim[1] - xlim[0]) * (1 + factor) 
axes.set_xlim(new_xlim)

I find this particularly useful when I want to zoom out or zoom in just a little from the default plot settings.


回答 6

这应该工作。您的代码对我有效,例如Tamás和Manoj Govindan。看来您可以尝试更新Matplotlib。如果您无法更新Matplotlib(例如,如果您的管理权限不足),也许使用其他后端matplotlib.use()可能会有所帮助。

This should work. Your code works for me, like for Tamás and Manoj Govindan. It looks like you could try to update Matplotlib. If you can’t update Matplotlib (for instance if you have insufficient administrative rights), maybe using a different backend with matplotlib.use() could help.


回答 7

仅用于微调。如果只想设置轴的一个边界,而另一个边界不变,则可以选择以下一个或多个语句

plt.xlim(right=xmax) #xmax is your value
plt.xlim(left=xmin) #xmin is your value
plt.ylim(top=ymax) #ymax is your value
plt.ylim(bottom=ymin) #ymin is your value

查看有关xlimylim的文档

Just for fine tuning. If you want to set only one of the boundaries of the axis and let the other boundary unchanged, you can choose one or more of the following statements

plt.xlim(right=xmax) #xmax is your value
plt.xlim(left=xmin) #xmin is your value
plt.ylim(top=ymax) #ymax is your value
plt.ylim(bottom=ymin) #ymin is your value

Take a look at the documentation for xlim and for ylim


回答 8

如果某个轴(由问题下方代码下方的代码生成)与第一个轴共享范围,请确保将范围设置为该轴的最后一个绘图之后

If an axes (generated by code below the code shown in the question) is sharing the range with the first axes, make sure that you set the range after the last plot of that axes.


如何使IPython Notebook Matplotlib内联绘图

问题:如何使IPython Notebook Matplotlib内联绘图

我正在MacOS X上使用Python 2.7.2和IPython 1.1.0的情况下使用IPython Notebook。

我无法获得matplotlib图形来内联显示。

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

我也试过了%pylab inline和ipython命令行参数,--pylab=inline但这没什么区别。

x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp')
plt.show()

我得到的不是内联图形,而是:

<matplotlib.figure.Figure at 0x110b9c450>

matplotlib.get_backend()表明我有'module://IPython.kernel.zmq.pylab.backend_inline'后端。

I am trying to use IPython notebook on MacOS X with Python 2.7.2 and IPython 1.1.0.

I cannot get matplotlib graphics to show up inline.

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

I have also tried %pylab inline and the ipython command line arguments --pylab=inline but this makes no difference.

x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp')
plt.show()

Instead of inline graphics, I get this:

<matplotlib.figure.Figure at 0x110b9c450>

And matplotlib.get_backend() shows that I have the 'module://IPython.kernel.zmq.pylab.backend_inline' backend.


回答 0

%matplotlib inline在笔记本的第一个单元中使用了它,并且可以正常工作。我认为您应该尝试:

%matplotlib inline

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

通过在配置文件中设置以下配置选项,默认情况下,您也始终可以始终默认以内联模式启动所有IPython内核:

c.IPKernelApp.matplotlib=<CaselessStrEnum>
  Default: None
  Choices: ['auto', 'gtk', 'gtk3', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt4', 'qt5', 'tk', 'wx']
  Configure matplotlib for interactive use with the default matplotlib backend.

I used %matplotlib inline in the first cell of the notebook and it works. I think you should try:

%matplotlib inline

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

You can also always start all your IPython kernels in inline mode by default by setting the following config options in your config files:

c.IPKernelApp.matplotlib=<CaselessStrEnum>
  Default: None
  Choices: ['auto', 'gtk', 'gtk3', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt4', 'qt5', 'tk', 'wx']
  Configure matplotlib for interactive use with the default matplotlib backend.

回答 1

如果您的matplotlib版本高于1.4,则也可以使用

IPython 3.x及更高版本

%matplotlib notebook

import matplotlib.pyplot as plt

旧版本

%matplotlib nbagg

import matplotlib.pyplot as plt

两者都将激活nbagg后端,从而启用交互性。

If your matplotlib version is above 1.4, it is also possible to use

IPython 3.x and above

%matplotlib notebook

import matplotlib.pyplot as plt

older versions

%matplotlib nbagg

import matplotlib.pyplot as plt

Both will activate the nbagg backend, which enables interactivity.


回答 2

Ctrl + Enter

%matplotlib inline

魔线:D

请参阅:使用Matplotlib进行绘图

Ctrl + Enter

%matplotlib inline

Magic Line :D

See: Plotting with Matplotlib.


回答 3

使用%pylab inline魔术命令。

Use the %pylab inline magic command.


回答 4

要在Jupyter(IPython 3)中默认使matplotlib内联:

  1. 编辑档案 ~/.ipython/profile_default/ipython_config.py

  2. 加线 c.InteractiveShellApp.matplotlib = 'inline'

请注意,添加该行将ipython_notebook_config.py不起作用。否则,它可以与Jupyter和IPython 3.1.0一起使用

To make matplotlib inline by default in Jupyter (IPython 3):

  1. Edit file ~/.ipython/profile_default/ipython_config.py

  2. Add line c.InteractiveShellApp.matplotlib = 'inline'

Please note that adding this line to ipython_notebook_config.py would not work. Otherwise it works well with Jupyter and IPython 3.1.0


回答 5

我必须同意foobarbecue(我的建议不足,无法简单地在他的帖子下插入评论):

--pylab根据Fernando Perez(ipythonnb的创建者)的说法,现在建议不要使用该参数启动python笔记本。%matplotlib inline应该是笔记本的初始命令。

看到这里:http : //nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/notebooks/Part%203%20-%20Plotting%20with%20Matplotlib.ipynb

I have to agree with foobarbecue (I don’t have enough recs to be able to simply insert a comment under his post):

It’s now recommended that python notebook isn’t started wit the argument --pylab, and according to Fernando Perez (creator of ipythonnb) %matplotlib inline should be the initial notebook command.

See here: http://nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/notebooks/Part%203%20-%20Plotting%20with%20Matplotlib.ipynb


回答 6

我找到了一种非常令人满意的解决方法。我安装了Anaconda Python,现在对我来说开箱即用。

I found a workaround that is quite satisfactory. I installed Anaconda Python and this now works out of the box for me.


回答 7

我做了anaconda安装,但是matplotlib没有绘制

当我这样做时它开始绘图

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

I did the anaconda install but matplotlib is not plotting

It starts plotting when i did this

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

回答 8

您可以使用语法错误来模拟此问题,但是%matplotlib inline无法解决该问题。

首先是创建绘图的正确方法的示例。eNord9提供的导入内容和魔术可以使一切正常工作。

df_randNumbers1 = pd.DataFrame(np.random.randint(0,100,size=(100, 6)), columns=list('ABCDEF'))

df_randNumbers1.ix[:,["A","B"]].plot.kde()

但是,通过将()绘图类型的末尾保留为空白,您会收到含糊不清的非错误。

错误代码:

df_randNumbers1.ix[:,["A","B"]].plot.kde

错误示例:

<bound method FramePlotMethods.kde of <pandas.tools.plotting.FramePlotMethods object at 0x000001DDAF029588>>

除了这一行消息外,没有堆栈跟踪或其他明显的理由认为您犯了语法错误。该图不打印。

You can simulate this problem with a syntax mistake, however, %matplotlib inline won’t resolve the issue.

First an example of the right way to create a plot. Everything works as expected with the imports and magic that eNord9 supplied.

df_randNumbers1 = pd.DataFrame(np.random.randint(0,100,size=(100, 6)), columns=list('ABCDEF'))

df_randNumbers1.ix[:,["A","B"]].plot.kde()

However, by leaving the () off the end of the plot type you receive a somewhat ambiguous non-error.

Erronious code:

df_randNumbers1.ix[:,["A","B"]].plot.kde

Example error:

<bound method FramePlotMethods.kde of <pandas.tools.plotting.FramePlotMethods object at 0x000001DDAF029588>>

Other than this one line message, there is no stack trace or other obvious reason to think you made a syntax error. The plot doesn’t print.


回答 9

在Jupyter的单独单元中运行绘图命令时,我遇到了同样的问题:

In [1]:  %matplotlib inline
         import matplotlib
         import matplotlib.pyplot as plt
         import numpy as np
In [2]:  x = np.array([1, 3, 4])
         y = np.array([1, 5, 3])
In [3]:  fig = plt.figure()
         <Figure size 432x288 with 0 Axes>                      #this might be the problem
In [4]:  ax = fig.add_subplot(1, 1, 1)
In [5]:  ax.scatter(x, y)
Out[5]:  <matplotlib.collections.PathCollection at 0x12341234>  # CAN'T SEE ANY PLOT :(
In [6]:  plt.show()                                             # STILL CAN'T SEE IT :(

通过将绘图命令合并到单个单元格中解决了该问题:

In [1]:  %matplotlib inline
         import matplotlib
         import matplotlib.pyplot as plt
         import numpy as np
In [2]:  x = np.array([1, 3, 4])
         y = np.array([1, 5, 3])
In [3]:  fig = plt.figure()
         ax = fig.add_subplot(1, 1, 1)
         ax.scatter(x, y)
Out[3]:  <matplotlib.collections.PathCollection at 0x12341234>
         # AND HERE APPEARS THE PLOT AS DESIRED :)

I had the same problem when I was running the plotting commands in separate cells in Jupyter:

In [1]:  %matplotlib inline
         import matplotlib
         import matplotlib.pyplot as plt
         import numpy as np
In [2]:  x = np.array([1, 3, 4])
         y = np.array([1, 5, 3])
In [3]:  fig = plt.figure()
         <Figure size 432x288 with 0 Axes>                      #this might be the problem
In [4]:  ax = fig.add_subplot(1, 1, 1)
In [5]:  ax.scatter(x, y)
Out[5]:  <matplotlib.collections.PathCollection at 0x12341234>  # CAN'T SEE ANY PLOT :(
In [6]:  plt.show()                                             # STILL CAN'T SEE IT :(

The problem was solved by merging the plotting commands into a single cell:

In [1]:  %matplotlib inline
         import matplotlib
         import matplotlib.pyplot as plt
         import numpy as np
In [2]:  x = np.array([1, 3, 4])
         y = np.array([1, 5, 3])
In [3]:  fig = plt.figure()
         ax = fig.add_subplot(1, 1, 1)
         ax.scatter(x, y)
Out[3]:  <matplotlib.collections.PathCollection at 0x12341234>
         # AND HERE APPEARS THE PLOT AS DESIRED :)

您如何更改用matplotlib绘制的图形的大小?

问题:您如何更改用matplotlib绘制的图形的大小?

如何更改用matplotlib绘制的图形的大小?

How do you change the size of figure drawn with matplotlib?


回答 0

该图告诉您呼叫签名:

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

figure(figsize=(1,1)) 会创建一个一英寸一英寸的图像,该图像将是80 x 80像素,除非您还指定了不同的dpi参数。

figure tells you the call signature:

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

figure(figsize=(1,1)) would create an inch-by-inch image, which would be 80-by-80 pixels unless you also give a different dpi argument.


回答 1

如果您已经创建了图形,则可以快速执行以下操作:

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)

If you’ve already got the figure created you can quickly do this:

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

To propagate the size change to an existing gui window add forward=True

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

回答 2

弃用说明:
根据官方Matplotlib指南pylab不再建议使用该模块。请考虑使用该matplotlib.pyplot模块,如该其他答案所述

以下似乎有效:

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

这使图形的宽度为5英寸,高度为10 英寸

然后,Figure类将其用作其参数之一的默认值。

Deprecation note:
As per the official Matplotlib guide, usage of the pylab module is no longer recommended. Please consider using the matplotlib.pyplot module instead, as described by this other answer.

The following seems to work:

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

This makes the figure’s width 5 inches, and its height 10 inches.

The Figure class then uses this as the default value for one of its arguments.


回答 3

使用plt.rcParams

如果您想在不使用图形环境的情况下更改大小,也可以使用此解决方法。因此,plt.plot()例如在使用时,可以设置宽度和高度的元组。

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

当您以内联方式绘制时(例如,使用IPython Notebook),这非常有用。正如@asamaier所注意的那样,最好不要将此语句放在import语句的同一单元格中。

转换为厘米

figsize元组接受英寸所以,如果你想将其设置成你必须2.54分他们厘米,看一下这个问题

USING plt.rcParams

There is also this workaround in case you want to change the size without using the figure environment. So in case you are using plt.plot() for example, you can set a tuple with width and height.

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

This is very useful when you plot inline (e.g. with IPython Notebook). As @asamaier noticed is preferable to not put this statement in the same cell of the imports statements.

Conversion to cm

The figsize tuple accepts inches so if you want to set it in centimetres you have to divide them by 2.54 have a look to this question.


回答 4

请尝试以下简单代码:

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

在绘制之前,需要设置图形尺寸。

Please try a simple code as following:

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

You need to set the figure size before you plot.


回答 5

如果您正在寻找一种方法来更改Pandas中的图形大小,可以执行例如:

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

df熊猫数据框在哪里。或者,使用现有图形或轴

fig, ax = plt.subplots(figsize=(10,5))
df['some_column'].plot(ax=ax)

如果要更改默认设置,可以执行以下操作:

import matplotlib

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

In case you’re looking for a way to change the figure size in Pandas, you could do e.g.:

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

where df is a Pandas dataframe. Or, to use existing figure or axes

fig, ax = plt.subplots(figsize=(10,5))
df['some_column'].plot(ax=ax)

If you want to change the default settings, you could do the following:

import matplotlib

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

回答 6

Google中的第一个链接'matplotlib figure size'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.]

两个注意事项:

  1. 模块注释和实际输出不同。

  2. 通过此答案,可以轻松地将所有三个图像合并到一个图像文件中,以查看大小的差异。

The first link in Google for 'matplotlib figure size' is AdjustingImageSize (Google cache of the page).

Here’s a test script from the above page. It creates test[1-3].png files of different sizes of the same image:

#!/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.

Output:

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.]

Two notes:

  1. The module comments and the actual output differ.

  2. This answer allows easily to combine all three images in one image file to see the difference in sizes.


回答 7

您可以简单地使用(来自matplotlib.figure.Figure):

fig.set_size_inches(width,height)

从Matplotlib 2.0.0开始,对画布的更改将立即可见,因为forward关键字默认为True

如果您只想更改宽度高度而不是两者,则可以使用

fig.set_figwidth(val) 要么 fig.set_figheight(val)

这些也将立即更新您的画布,但仅限于Matplotlib 2.2.0和更高版本。

对于较旧的版本

您需要forward=True明确指定以便实时更新比上面指定的版本更早的画布。请注意,在Matplotlib 1.5.0之前的版本中,set_figwidthand set_figheight函数不支持该forward参数。

You can simply use (from matplotlib.figure.Figure):

fig.set_size_inches(width,height)

As of Matplotlib 2.0.0, changes to your canvas will be visible immediately, as the forward keyword defaults to True.

If you want to just change the width or height instead of both, you can use

fig.set_figwidth(val) or fig.set_figheight(val)

These will also immediately update your canvas, but only in Matplotlib 2.2.0 and newer.

For Older Versions

You need to specify forward=True explicitly in order to live-update your canvas in versions older than what is specified above. Note that the set_figwidth and set_figheight functions don’t support the forward parameter in versions older than Matplotlib 1.5.0.


回答 8

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))
import matplotlib.pyplot as plt
plt.figure(figsize=(20,10))
plt.plot(x,y) ## This is your plot
plt.show()

You can also use:

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

回答 9

尝试注释掉该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()

Try commenting out the fig = ... line

%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()

回答 10

这对我来说很好:

from matplotlib import pyplot as plt

F = plt.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

This works well for me:

from matplotlib import pyplot as plt

F = plt.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

This might also help: http://matplotlib.1069221.n5.nabble.com/Resizing-figure-windows-td11424.html


回答 11

要增加N倍的图形大小,您需要在pl.show()之前插入它:

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

它也可以与ipython notebook一起很好地工作。

To increase size of your figure N times you need to insert this just before your pl.show():

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

It also works well with ipython notebook.


回答 12

由于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))

Since Matplotlib isn’t able to use the metric system natively, if you want to specify the size of your figure in a reasonable unit of length such as centimeters, you can do the following (code from 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)

Then you can use:

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

回答 13

即使在绘制图形之后,这也会立即调整图形的大小(至少使用带有matplotlib 1.4.0的Qt4Agg / TkAgg-但不使用MacOSX-):

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

This resizes the figure immediately even after the figure has been drawn (at least using Qt4Agg/TkAgg – but not MacOSX – with matplotlib 1.4.0):

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

回答 14

概括和简化psihodelia的答案。如果您想将图形的当前大小更改一个因子sizefactor

import matplotlib.pyplot as plt

# here goes your code

fig_size = plt.gcf().get_size_inches() #Get current size
sizefactor = 0.8 #Set a zoom factor
# Modify the current size by the factor
plt.gcf().set_size_inches(sizefactor * fig_size) 

更改当前大小后,可能需要微调子图布局。您可以在图形窗口GUI中执行此操作,也可以通过命令subplots_adjust进行操作

例如,

plt.subplots_adjust(left=0.16, bottom=0.19, top=0.82)

Generalizing and simplifying psihodelia’s answer. If you want to change the current size of the figure by a factor sizefactor

import matplotlib.pyplot as plt

# here goes your code

fig_size = plt.gcf().get_size_inches() #Get current size
sizefactor = 0.8 #Set a zoom factor
# Modify the current size by the factor
plt.gcf().set_size_inches(sizefactor * fig_size) 

After changing the current size, it might occur that you have to fine tune the subplot layout. You can do that in the figure window GUI, or by means of the command subplots_adjust

For example,

plt.subplots_adjust(left=0.16, bottom=0.19, top=0.82)

回答 15

另一种选择是在matplotlib中使用rc()函数(单位为英寸)

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

Another option, to use the rc() function in matplotlib (the unit is inch)

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

回答 16

您可以通过直接更改图形尺寸

plt.set_figsize(figure=(10, 10))

You directly change the figure size by using

plt.set_figsize(figure=(10, 10))

将绘图保存到图像文件,而不是使用Matplotlib显示

问题:将绘图保存到图像文件,而不是使用Matplotlib显示

我正在编写一个快速脚本来动态生成绘图。我使用下面的代码(来自Matplotlib文档)作为起点:

from pylab import figure, axes, pie, title, show

# Make a square figure and axes
figure(1, figsize=(6, 6))
ax = axes([0.1, 0.1, 0.8, 0.8])

labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]

explode = (0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
title('Raining Hogs and Dogs', bbox={'facecolor': '0.8', 'pad': 5})

show()  # Actually, don't show, just save to foo.png

我不想将图形显示在GUI上,而是要将图形保存到文件(例如foo.png)中,以便可以在批处理脚本中使用它。我怎么做?

I am writing a quick-and-dirty script to generate plots on the fly. I am using the code below (from Matplotlib documentation) as a starting point:

from pylab import figure, axes, pie, title, show

# Make a square figure and axes
figure(1, figsize=(6, 6))
ax = axes([0.1, 0.1, 0.8, 0.8])

labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]

explode = (0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
title('Raining Hogs and Dogs', bbox={'facecolor': '0.8', 'pad': 5})

show()  # Actually, don't show, just save to foo.png

I don’t want to display the plot on a GUI, instead, I want to save the plot to a file (say foo.png), so that, for example, it can be used in batch scripts. How do I do that?


回答 0

在回答问题后,我想在使用matplotlib.pyplot.savefig时添加一些有用的提示。文件格式可以通过扩展名指定:

from matplotlib import pyplot as plt

plt.savefig('foo.png')
plt.savefig('foo.pdf')

将分别给出栅格化或矢量化的输出,这两个都可能有用。此外,您会发现pylab在图像周围留有大量的空白,通常是不希望的空白。使用以下方法删除它:

savefig('foo.png', bbox_inches='tight')

While the question has been answered, I’d like to add some useful tips when using matplotlib.pyplot.savefig. The file format can be specified by the extension:

from matplotlib import pyplot as plt

plt.savefig('foo.png')
plt.savefig('foo.pdf')

Will give a rasterized or vectorized output respectively, both which could be useful. In addition, you’ll find that pylab leaves a generous, often undesirable, whitespace around the image. Remove it with:

savefig('foo.png', bbox_inches='tight')

回答 1

正如其他人所说的,plt.savefig()或者fig1.savefig()确实是保存图像的方法。

但是我发现在某些情况下总是显示该图。(例如,在Spyder具有plt.ion():交互模式= On的情况下)。我通过强制关闭巨型循环中的图形窗口来解决此问题plt.close(figure_object)(请参阅文档),因此在循环中没有一百万个开放图形:

import matplotlib.pyplot as plt
fig, ax = plt.subplots( nrows=1, ncols=1 )  # create figure & 1 axis
ax.plot([0,1,2], [10,20,3])
fig.savefig('path/to/save/image/to.png')   # save the figure to file
plt.close(fig)    # close the figure window

如有需要,您应该可以重新打开该图fig.show()(不必测试自己)。

As others have said, plt.savefig() or fig1.savefig() is indeed the way to save an image.

However I’ve found that in certain cases the figure is always shown. (eg. with Spyder having plt.ion(): interactive mode = On.) I work around this by forcing the closing of the figure window in my giant loop with plt.close(figure_object) (see documentation), so I don’t have a million open figures during the loop:

import matplotlib.pyplot as plt
fig, ax = plt.subplots( nrows=1, ncols=1 )  # create figure & 1 axis
ax.plot([0,1,2], [10,20,3])
fig.savefig('path/to/save/image/to.png')   # save the figure to file
plt.close(fig)    # close the figure window

You should be able to re-open the figure later if needed to with fig.show() (didn’t test myself).


回答 2

解决方案是:

pylab.savefig('foo.png')

The solution is:

pylab.savefig('foo.png')

回答 3

刚在MatPlotLib文档中找到此链接,可以解决此问题: http

他们说,防止图形弹出的最简单方法是通过使用非交互式后端(例如Agg)matplotib.use(<backend>),例如:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('myfig')

我个人还是喜欢使用 plt.close( fig ),因为从那时起,您可以选择隐藏某些图形(在循环过程中),但仍显示图形以进行循环后数据处理。不过,它可能比选择非交互式后端要慢-如果有人对此进行了测试,那将很有趣。

更新:对于Spyder,您通常无法以这种方式设置后端(因为Spyder通常会较早加载matplotlib,从而阻止您使用matplotlib.use())。

而是在Spyder偏好设置中使用plt.switch_backend('Agg')或关闭“ 启用支持 ”,然后运行matplotlib.use('Agg')自己命令。

从这两个提示:

Just found this link on the MatPlotLib documentation addressing exactly this issue: http://matplotlib.org/faq/howto_faq.html#generate-images-without-having-a-window-appear

They say that the easiest way to prevent the figure from popping up is to use a non-interactive backend (eg. Agg), via matplotib.use(<backend>), eg:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('myfig')

I still personally prefer using plt.close( fig ), since then you have the option to hide certain figures (during a loop), but still display figures for post-loop data processing. It is probably slower than choosing a non-interactive backend though – would be interesting if someone tested that.

UPDATE: for Spyder, you usually can’t set the backend in this way (Because Spyder usually loads matplotlib early, preventing you from using matplotlib.use()).

Instead, use plt.switch_backend('Agg'), or Turn off “enable support” in the Spyder prefs and run the matplotlib.use('Agg') command yourself.

From these two hints: one, two


回答 4

如果您不喜欢“当前”数字的概念,请执行以下操作:

import matplotlib.image as mpimg

img = mpimg.imread("src.png")
mpimg.imsave("out.png", img)

If you don’t like the concept of the “current” figure, do:

import matplotlib.image as mpimg

img = mpimg.imread("src.png")
mpimg.imsave("out.png", img)

回答 5

其他答案是正确的。但是,有时我发现我想稍后再打开图形对象。例如,我可能想更改标签大小,添加网格或进行其他处理。在理想的情况下,我只需要重新运行生成图的代码并修改设置即可。las,世界并不完美。因此,除了保存为PDF或PNG之外,我还添加:

with open('some_file.pkl', "wb") as fp:
    pickle.dump(fig, fp, protocol=4)

这样,以后我可以加载图形对象并根据需要操纵设置。

我还用源代码写出了堆栈, locals()每个函数/方法字典的堆栈,以便以后可以准确地知道是什么产生了该图。

注意:请小心,因为有时此方法会生成巨大的文件。

The other answers are correct. However, I sometimes find that I want to open the figure object later. For example, I might want to change the label sizes, add a grid, or do other processing. In a perfect world, I would simply rerun the code generating the plot, and adapt the settings. Alas, the world is not perfect. Therefore, in addition to saving to PDF or PNG, I add:

with open('some_file.pkl', "wb") as fp:
    pickle.dump(fig, fp, protocol=4)

Like this, I can later load the figure object and manipulate the settings as I please.

I also write out the stack with the source-code and locals() dictionary for each function/method in the stack, so that I can later tell exactly what generated the figure.

NB: Be careful, as sometimes this method generates huge files.


回答 6

import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
with PdfPages('multipage_pdf.pdf') as pdf:
    plt.figure(figsize=(3, 3))
    plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
    plt.title('Page One')
    pdf.savefig()  # saves the current figure into a pdf page
    plt.close()

    plt.rc('text', usetex=True)
    plt.figure(figsize=(8, 6))
    x = np.arange(0, 5, 0.1)
    plt.plot(x, np.sin(x), 'b-')
    plt.title('Page Two')
    pdf.savefig()
    plt.close()

    plt.rc('text', usetex=False)
    fig = plt.figure(figsize=(4, 5))
    plt.plot(x, x*x, 'ko')
    plt.title('Page Three')
    pdf.savefig(fig)  # or you can pass a Figure object to pdf.savefig
    plt.close()

    # We can also set the file's metadata via the PdfPages object:
    d = pdf.infodict()
    d['Title'] = 'Multipage PDF Example'
    d['Author'] = u'Jouni K. Sepp\xe4nen'
    d['Subject'] = 'How to create a multipage pdf file and set its metadata'
    d['Keywords'] = 'PdfPages multipage keywords author title subject'
    d['CreationDate'] = datetime.datetime(2009, 11, 13)
    d['ModDate'] = datetime.datetime.today()
import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
with PdfPages('multipage_pdf.pdf') as pdf:
    plt.figure(figsize=(3, 3))
    plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
    plt.title('Page One')
    pdf.savefig()  # saves the current figure into a pdf page
    plt.close()

    plt.rc('text', usetex=True)
    plt.figure(figsize=(8, 6))
    x = np.arange(0, 5, 0.1)
    plt.plot(x, np.sin(x), 'b-')
    plt.title('Page Two')
    pdf.savefig()
    plt.close()

    plt.rc('text', usetex=False)
    fig = plt.figure(figsize=(4, 5))
    plt.plot(x, x*x, 'ko')
    plt.title('Page Three')
    pdf.savefig(fig)  # or you can pass a Figure object to pdf.savefig
    plt.close()

    # We can also set the file's metadata via the PdfPages object:
    d = pdf.infodict()
    d['Title'] = 'Multipage PDF Example'
    d['Author'] = u'Jouni K. Sepp\xe4nen'
    d['Subject'] = 'How to create a multipage pdf file and set its metadata'
    d['Keywords'] = 'PdfPages multipage keywords author title subject'
    d['CreationDate'] = datetime.datetime(2009, 11, 13)
    d['ModDate'] = datetime.datetime.today()

回答 7

在使用plot()和其他函数创建所需的内容之后,可以使用如下子句在绘制到屏幕或文件之间进行选择:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(4, 5))       # size in inches
# use plot(), etc. to create your plot.

# Pick one of the following lines to uncomment
# save_file = None
# save_file = os.path.join(your_directory, your_file_name)  

if save_file:
    plt.savefig(save_file)
    plt.close(fig)
else:
    plt.show()

After using the plot() and other functions to create the content you want, you could use a clause like this to select between plotting to the screen or to file:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(4, 5))       # size in inches
# use plot(), etc. to create your plot.

# Pick one of the following lines to uncomment
# save_file = None
# save_file = os.path.join(your_directory, your_file_name)  

if save_file:
    plt.savefig(save_file)
    plt.close(fig)
else:
    plt.show()

回答 8

我使用了以下内容:

import matplotlib.pyplot as plt

p1 = plt.plot(dates, temp, 'r-', label="Temperature (celsius)")  
p2 = plt.plot(dates, psal, 'b-', label="Salinity (psu)")  
plt.legend(loc='upper center', numpoints=1, bbox_to_anchor=(0.5, -0.05),        ncol=2, fancybox=True, shadow=True)

plt.savefig('data.png')  
plt.show()  
f.close()
plt.close()

保存数字后,我发现使用plt.show非常重要,否则它将无法正常工作。图以png格式导出

I used the following:

import matplotlib.pyplot as plt

p1 = plt.plot(dates, temp, 'r-', label="Temperature (celsius)")  
p2 = plt.plot(dates, psal, 'b-', label="Salinity (psu)")  
plt.legend(loc='upper center', numpoints=1, bbox_to_anchor=(0.5, -0.05),        ncol=2, fancybox=True, shadow=True)

plt.savefig('data.png')  
plt.show()  
f.close()
plt.close()

I found very important to use plt.show after saving the figure, otherwise it won’t work.figure exported in png


回答 9

您可以执行以下操作:

plt.show(hold=False)
plt.savefig('name.pdf')

并记得在关闭GUI图之前先让savefig完成。这样,您可以预先查看图像。

或者,你可以看看它plt.show() 然后关闭GUI,然后再次运行该脚本,但这次替换plt.show()plt.savefig()

或者,您可以使用

fig, ax = plt.figure(nrows=1, ncols=1)
plt.plot(...)
plt.show()
fig.savefig('out.pdf')

You can either do:

plt.show(hold=False)
plt.savefig('name.pdf')

and remember to let savefig finish before closing the GUI plot. This way you can see the image beforehand.

Alternatively, you can look at it with plt.show() Then close the GUI and run the script again, but this time replace plt.show() with plt.savefig().

Alternatively, you can use

fig, ax = plt.figure(nrows=1, ncols=1)
plt.plot(...)
plt.show()
fig.savefig('out.pdf')

回答 10

如果像我一样使用Spyder IDE,则必须使用以下命令禁用交互模式:

plt.ioff()

(此命令随科学启动一起自动启动)

如果要再次启用它,请使用:

plt.ion()

If, like me, you use Spyder IDE, you have to disable the interactive mode with :

plt.ioff()

(this command is automatically launched with the scientific startup)

If you want to enable it again, use :

plt.ion()


回答 11

解决方案 :

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
plt.figure()
ts.plot()
plt.savefig("foo.png", bbox_inches='tight')

如果确实要显示图像并保存图像,请使用:

%matplotlib inline

import matplotlib

The Solution :

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
plt.figure()
ts.plot()
plt.savefig("foo.png", bbox_inches='tight')

If you do want to display the image as well as saving the image use:

%matplotlib inline

after import matplotlib


回答 12

根据问题Matplotlib(pyplot)savefig输出空白图像

请注意一件事:如果使用plt.show,则应在之后plt.savefig,否则将给出空白图像。

详细的例子:

import numpy as np
import matplotlib.pyplot as plt


def draw_result(lst_iter, lst_loss, lst_acc, title):
    plt.plot(lst_iter, lst_loss, '-b', label='loss')
    plt.plot(lst_iter, lst_acc, '-r', label='accuracy')

    plt.xlabel("n iteration")
    plt.legend(loc='upper left')
    plt.title(title)
    plt.savefig(title+".png")  # should before plt.show method

    plt.show()


def test_draw():
    lst_iter = range(100)
    lst_loss = [0.01 * i + 0.01 * i ** 2 for i in xrange(100)]
    # lst_loss = np.random.randn(1, 100).reshape((100, ))
    lst_acc = [0.01 * i - 0.01 * i ** 2 for i in xrange(100)]
    # lst_acc = np.random.randn(1, 100).reshape((100, ))
    draw_result(lst_iter, lst_loss, lst_acc, "sgd_method")


if __name__ == '__main__':
    test_draw()

According to question Matplotlib (pyplot) savefig outputs blank image.

One thing should note: if you use plt.show and it should after plt.savefig, or you will give a blank image.

A detailed example:

import numpy as np
import matplotlib.pyplot as plt


def draw_result(lst_iter, lst_loss, lst_acc, title):
    plt.plot(lst_iter, lst_loss, '-b', label='loss')
    plt.plot(lst_iter, lst_acc, '-r', label='accuracy')

    plt.xlabel("n iteration")
    plt.legend(loc='upper left')
    plt.title(title)
    plt.savefig(title+".png")  # should before plt.show method

    plt.show()


def test_draw():
    lst_iter = range(100)
    lst_loss = [0.01 * i + 0.01 * i ** 2 for i in xrange(100)]
    # lst_loss = np.random.randn(1, 100).reshape((100, ))
    lst_acc = [0.01 * i - 0.01 * i ** 2 for i in xrange(100)]
    # lst_acc = np.random.randn(1, 100).reshape((100, ))
    draw_result(lst_iter, lst_loss, lst_acc, "sgd_method")


if __name__ == '__main__':
    test_draw()


回答 13

import matplotlib.pyplot as plt
plt.savefig("image.png")

在Jupyter Notebook中,您必须在一个单元格中删除plt.show()并添加plt.savefig(),以及其余的plt代码。该图像仍将显示在笔记本中。

import matplotlib.pyplot as plt
plt.savefig("image.png")

In Jupyter Notebook you have to remove plt.show() and add plt.savefig(), together with the rest of the plt-code in one cell. The image will still show up in your notebook.


回答 14

鉴于今天(提出此问题时尚不可用)很多人将Jupyter Notebook用作python控制台,所以有一种极为简单的方式将图保存为.png,只需从Jupyter Notebook 调用matplotlibpylab类,将图绘制为“内联” ‘jupyter单元格,然后将该图形/图像拖到本地目录。不要忘记 %matplotlib inline第一行!

Given that today (was not available when this question was made) lots of people use Jupyter Notebook as python console, there is an extremely easy way to save the plots as .png, just call the matplotlib‘s pylab class from Jupyter Notebook, plot the figure ‘inline’ jupyter cells, and then drag that figure/image to a local directory. Don’t forget %matplotlib inline in the first line!


回答 15

除了上述内容外,我还添加__file__了名称,以便图片和Python文件获得相同的名称。我还添加了一些参数使它看起来更好:

# Saves a PNG file of the current graph to the folder and updates it every time
# (nameOfimage, dpi=(sizeOfimage),Keeps_Labels_From_Disappearing)
plt.savefig(__file__+".png",dpi=(250), bbox_inches='tight')
# Hard coded name: './test.png'

Additionally to those above, I added __file__ for the name so the picture and Python file get the same names. I also added few arguments to make It look better:

# Saves a PNG file of the current graph to the folder and updates it every time
# (nameOfimage, dpi=(sizeOfimage),Keeps_Labels_From_Disappearing)
plt.savefig(__file__+".png",dpi=(250), bbox_inches='tight')
# Hard coded name: './test.png'

回答 16

使用时matplotlib.pyplot,必须先保存您的绘图,然后使用以下两行将其关闭:

fig.savefig('plot.png') # save the plot, place the path you want to save the figure in quotation
plt.close(fig) # close the figure window

When using matplotlib.pyplot, you must first save your plot and then close it using these 2 lines:

fig.savefig('plot.png') # save the plot, place the path you want to save the figure in quotation
plt.close(fig) # close the figure window

回答 17

如前所述,您可以使用:

import matplotlib.pyplot as plt
plt.savefig("myfig.png")

用于保存您正在显示的任何IPhython图像。或者换个角度(从另一个角度看),如果您曾经使用过开放式简历,或者如果您导入过开放式简历,则可以进行以下工作:

导入cv2

cv2.imwrite(“ myfig.png”,图像)

但这只是万一,如果您需要使用Open CV。否则,plt.savefig()应该足够。

As suggested before, you can either use:

import matplotlib.pyplot as plt
plt.savefig("myfig.png")

For saving whatever IPhython image that you are displaying. Or on a different note (looking from a different angle), if you ever get to work with open cv, or if you have open cv imported, you can go for:

import cv2

cv2.imwrite(“myfig.png”,image)

But this is just in case if you need to work with Open CV. Otherwise plt.savefig() should be sufficient.


回答 18

您可以使用任何扩展名(png,jpg等)并以所需的分辨率保存图像。这是保存您的身材的功能。

import os

def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300):
    path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension)
    print("Saving figure", fig_id)
    if tight_layout:
        plt.tight_layout()
    plt.savefig(path, format=fig_extension, dpi=resolution)

“ fig_id”是您要用来保存图形的名称。希望能帮助到你:)

You can save your image with any extension(png, jpg,etc.) and with the resolution you want. Here’s a function to save your figure.

import os

def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300):
    path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension)
    print("Saving figure", fig_id)
    if tight_layout:
        plt.tight_layout()
    plt.savefig(path, format=fig_extension, dpi=resolution)

‘fig_id’ is the name by which you want to save your figure. Hope it helps:)


回答 19

您可以这样做:

def plotAFig():
  plt.figure()
  plt.plot(x,y,'b-')
  plt.savefig("figurename.png")
  plt.close()

You can do it like this:

def plotAFig():
  plt.figure()
  plt.plot(x,y,'b-')
  plt.savefig("figurename.png")
  plt.close()

如何将图例排除在情节之外

问题:如何将图例排除在情节之外

我要在一个图中制作一系列20个图(不是子图)。我希望图例在框外。同时,由于图形尺寸变小,我不想更改轴。请帮助我进行以下查询:

  1. 我想将图例框保留在绘图区域之外。(我希望图例位于绘图区域的右侧)。
  2. 无论如何,我是否减小了图例框内文本的字体大小,以使图例框的大小变小。

I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure gets reduced. Kindly help me for the following queries:

  1. I want to keep the legend box outside the plot area. (I want the legend to be outside at the right side of the plot area).
  2. Is there anyway that I reduce the font size of the text inside the legend box, so that the size of the legend box will be small.

回答 0

您可以通过创建字体属性来缩小图例文本:

from matplotlib.font_manager import FontProperties

fontP = FontProperties()
fontP.set_size('small')
legend([plot1], "title", prop=fontP) 
# or add prop=fontP to whatever legend() call you already have

You can make the legend text smaller by creating font properties:

from matplotlib.font_manager import FontProperties

fontP = FontProperties()
fontP.set_size('small')
legend([plot1], "title", prop=fontP) 
# or add prop=fontP to whatever legend() call you already have

回答 1

有很多方法可以做您想要的。要添加@inalis和@Navi所说的内容,可以使用bbox_to_anchor关键字参数将图例部分地放置在轴外和/​​或减小字体大小。

在考虑减小字体大小(这可能使事情难以阅读)之前,请尝试将图例放在不同的位置:

因此,让我们从一个通用示例开始:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$' % i)

ax.legend()

plt.show()

如果我们做同样的事情,但是使用bbox_to_anchor关键字参数,我们可以将图例稍微移出轴边界:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$' % i)

ax.legend(bbox_to_anchor=(1.1, 1.05))

plt.show()

同样,您可以使图例更加水平和/或将其放在图的顶部(我也打开了圆角和简单的阴影):

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    line, = ax.plot(x, i * x, label='$y = %ix$'%i)

ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05),
          ncol=3, fancybox=True, shadow=True)
plt.show()

另外,您可以缩小当前图的宽度,并将图例完全放在图的轴外(注意:如果使用ight_layout(),则省略ax.set_position():

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$'%i)

# Shrink current axis by 20%
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])

# Put a legend to the right of the current axis
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

plt.show()

同样,您可以垂直缩小图,将水平图例放在底部:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    line, = ax.plot(x, i * x, label='$y = %ix$'%i)

# Shrink current axis's height by 10% on the bottom
box = ax.get_position()
ax.set_position([box.x0, box.y0 + box.height * 0.1,
                 box.width, box.height * 0.9])

# Put a legend below current axis
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
          fancybox=True, shadow=True, ncol=5)

plt.show()

看一下matplotlib图例指南。您也可以看看plt.figlegend()

There are a number of ways to do what you want. To add to what @inalis and @Navi already said, you can use the bbox_to_anchor keyword argument to place the legend partially outside the axes and/or decrease the font size.

Before you consider decreasing the font size (which can make things awfully hard to read), try playing around with placing the legend in different places:

So, let’s start with a generic example:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$' % i)

ax.legend()

plt.show()

If we do the same thing, but use the bbox_to_anchor keyword argument we can shift the legend slightly outside the axes boundaries:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$' % i)

ax.legend(bbox_to_anchor=(1.1, 1.05))

plt.show()

Similarly, you can make the legend more horizontal and/or put it at the top of the figure (I’m also turning on rounded corners and a simple drop shadow):

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    line, = ax.plot(x, i * x, label='$y = %ix$'%i)

ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05),
          ncol=3, fancybox=True, shadow=True)
plt.show()

Alternatively, you can shrink the current plot’s width, and put the legend entirely outside the axis of the figure (note: if you use tight_layout(), then leave out ax.set_position():

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$'%i)

# Shrink current axis by 20%
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])

# Put a legend to the right of the current axis
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

plt.show()

And in a similar manner, you can shrink the plot vertically, and put the a horizontal legend at the bottom:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    line, = ax.plot(x, i * x, label='$y = %ix$'%i)

# Shrink current axis's height by 10% on the bottom
box = ax.get_position()
ax.set_position([box.x0, box.y0 + box.height * 0.1,
                 box.width, box.height * 0.9])

# Put a legend below current axis
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
          fancybox=True, shadow=True, ncol=5)

plt.show()

Have a look at the matplotlib legend guide. You might also take a look at plt.figlegend().


回答 2

放置图例(bbox_to_anchor

通过使用loc参数将图例放置在轴的边界框内plt.legend
例如,loc="upper right"将图例放置在边界框的右上角,默认情况下,其坐标轴范围(或边界框符号)中从(0,0)到的范围。(1,1)(x0,y0, width, height)=(0,0,1,1)

要将图例放置在轴边界框之外,可以指定(x0,y0)图例左下角的坐标轴元组。

plt.legend(loc=(1.04,0))

但是,一种更通用的方法是使用bbox_to_anchor参数手动指定图例应放入的边框。可以限制自己只提供(x0,y0)bbox 的一部分。这将创建一个零跨度的框,图例将从该框沿loc参数给出的方向扩展。例如

plt.legend(bbox_to_anchor =(1.04,1),loc =“左上方”)

将图例放置在轴外,以使图例的左上角(1.04,1)位于轴坐标中的位置。

下面给出了进一步的示例,另外还显示了不同参数(例如mode和)之间的相互作用ncols

l1 = plt.legend(bbox_to_anchor=(1.04,1), borderaxespad=0)
l2 = plt.legend(bbox_to_anchor=(1.04,0), loc="lower left", borderaxespad=0)
l3 = plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)
l4 = plt.legend(bbox_to_anchor=(0,1.02,1,0.2), loc="lower left",
                mode="expand", borderaxespad=0, ncol=3)
l5 = plt.legend(bbox_to_anchor=(1,0), loc="lower right", 
                bbox_transform=fig.transFigure, ncol=3)
l6 = plt.legend(bbox_to_anchor=(0.4,0.8), loc="upper right")

要如何解释4元组参数的详细信息bbox_to_anchor,如l4,可以在发现这个问题。的mode="expand"由4元组给出的边界框内水平方向扩展的图例。有关纵向扩展的图例,请参见此问题

有时,在图形坐标而不是轴坐标中指定边界框可能会很有用。l5上面的示例中显示了这一点,其中该bbox_transform参数用于将图例放在图的左下角。

后期处理

将图例放置在轴外通常会导致不希望有的情况,即图例完全或部分位于花样画布之外。

解决此问题的方法是:

  • 调整子图参数
    可以使用来调整子图参数,以使轴在图形内占据更少的空间(从而为图例留出更多空间)plt.subplots_adjust。例如

    plt.subplots_adjust(right=0.7)

    在图的右侧留出30%的空间,可在其中放置图例。

  • 紧密布局
    使用“ plt.tight_layout允许”自动调整子图参数,以使图形中的元素紧贴图形边缘。不幸的是,在这种自动机制中没有考虑到图例,但是我们可以提供一个矩形框,整个子图区域(包括标签)都将适合该矩形框。

    plt.tight_layout(rect=[0,0,0.75,1])
  • 保存与数字bbox_inches = "tight"
    的参数bbox_inches = "tight",以plt.savefig可以用来保存数字使得画布(包括图例)上的所有艺术家被装配到已保存的区域。如果需要,图形尺寸会自动调整。

    plt.savefig("output.png", bbox_inches="tight")
  • 自动调整子图参数可以在以下答案中找到
    一种自动调整子图位置的方法,以使图例适合画布内部而无需更改图形尺寸创建具有精确尺寸且没有填充的图形(以及图例位于轴外)

上述案例之间的比较:

备择方案

图形说明
图例可以对图形使用图例,而不是轴matplotlib.figure.Figure.legend。这对于matplotlib版本> = 2.1尤其有用,在该版本中不需要特殊参数

fig.legend(loc=7) 

为图中不同轴上的所有艺术家创建一个图例。图例使用自loc变量放置,类似于如何将其放置在轴内,但参考的是整个图形-因此,图例将自动在轴外。剩下的就是调整子图,以使图例和轴之间没有重叠。上面的“调整子图​​参数” 点将很有帮助。一个例子:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,2*np.pi)
colors=["#7aa0c4","#ca82e1" ,"#8bcd50","#e18882"]
fig, axes = plt.subplots(ncols=2)
for i in range(4):
    axes[i//2].plot(x,np.sin(x+i), color=colors[i],label="y=sin(x+{})".format(i))

fig.legend(loc=7)
fig.tight_layout()
fig.subplots_adjust(right=0.75)   
plt.show()

专用子图轴内的图例
替代使用的bbox_to_anchor方法是将图例放置在其专用子图轴(lax)中。由于图例子图应该小于图,因此我们可以gridspec_kw={"width_ratios":[4,1]}在轴创建时使用它。我们可以隐藏轴,lax.axis("off")但仍然可以放置图例。图例的句柄和标签需要通过来从实际图获得h,l = ax.get_legend_handles_labels(),然后可以在lax子图中将其提供给图例lax.legend(h,l)。下面是一个完整的示例。

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = 6,2

fig, (ax,lax) = plt.subplots(ncols=2, gridspec_kw={"width_ratios":[4,1]})
ax.plot(x,y, label="y=sin(x)")
....

h,l = ax.get_legend_handles_labels()
lax.legend(h,l, borderaxespad=0)
lax.axis("off")

plt.tight_layout()
plt.show()

这将产生一个在视觉上与上面的图非常相似的图:

我们也可以使用第一个轴放置图例,但是使用bbox_transform图例轴的,

ax.legend(bbox_to_anchor=(0,0,1,1), bbox_transform=lax.transAxes)
lax.axis("off")

在这种方法中,我们不需要从外部获取图例句柄,但是需要指定bbox_to_anchor参数。

进一步阅读和注意事项:

  • 考虑一下matplotlib 图例指南,以及一些您想对图例进行处理的其他示例。
  • 可以直接在以下问题的答案中找到一些用于放置饼图图例的示例代码:Python-图例与饼图重叠
  • loc参数可以使用数字而不是字符串,这会使调用更短,但是,它们之间并不是很直观地相互映射。这是供参考的映射:

Placing the legend (bbox_to_anchor)

A legend is positioned inside the bounding box of the axes using the loc argument to plt.legend.
E.g. loc="upper right" places the legend in the upper right corner of the bounding box, which by default extents from (0,0) to (1,1) in axes coordinates (or in bounding box notation (x0,y0, width, height)=(0,0,1,1)).

To place the legend outside of the axes bounding box, one may specify a tuple (x0,y0) of axes coordinates of the lower left corner of the legend.

plt.legend(loc=(1.04,0))

However, a more versatile approach would be to manually specify the bounding box into which the legend should be placed, using the bbox_to_anchor argument. One can restrict oneself to supply only the (x0,y0) part of the bbox. This creates a zero span box, out of which the legend will expand in the direction given by the loc argument. E.g.

plt.legend(bbox_to_anchor=(1.04,1), loc="upper left")

places the legend outside the axes, such that the upper left corner of the legend is at position (1.04,1) in axes coordinates.

Further examples are given below, where additionally the interplay between different arguments like mode and ncols are shown.

l1 = plt.legend(bbox_to_anchor=(1.04,1), borderaxespad=0)
l2 = plt.legend(bbox_to_anchor=(1.04,0), loc="lower left", borderaxespad=0)
l3 = plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)
l4 = plt.legend(bbox_to_anchor=(0,1.02,1,0.2), loc="lower left",
                mode="expand", borderaxespad=0, ncol=3)
l5 = plt.legend(bbox_to_anchor=(1,0), loc="lower right", 
                bbox_transform=fig.transFigure, ncol=3)
l6 = plt.legend(bbox_to_anchor=(0.4,0.8), loc="upper right")

Details about how to interpret the 4-tuple argument to bbox_to_anchor, as in l4, can be found in this question. The mode="expand" expands the legend horizontally inside the bounding box given by the 4-tuple. For a vertically expanded legend, see this question.

Sometimes it may be useful to specify the bounding box in figure coordinates instead of axes coordinates. This is shown in the example l5 from above, where the bbox_transform argument is used to put the legend in the lower left corner of the figure.

Postprocessing

Having placed the legend outside the axes often leads to the undesired situation that it is completely or partially outside the figure canvas.

Solutions to this problem are:

  • Adjust the subplot parameters
    One can adjust the subplot parameters such, that the axes take less space inside the figure (and thereby leave more space to the legend) by using plt.subplots_adjust. E.g.

    plt.subplots_adjust(right=0.7)
    

    leaves 30% space on the right-hand side of the figure, where one could place the legend.

  • Tight layout
    Using plt.tight_layout Allows to automatically adjust the subplot parameters such that the elements in the figure sit tight against the figure edges. Unfortunately, the legend is not taken into account in this automatism, but we can supply a rectangle box that the whole subplots area (including labels) will fit into.

    plt.tight_layout(rect=[0,0,0.75,1])
    
  • Saving the figure with bbox_inches = "tight"
    The argument bbox_inches = "tight" to plt.savefig can be used to save the figure such that all artist on the canvas (including the legend) are fit into the saved area. If needed, the figure size is automatically adjusted.

    plt.savefig("output.png", bbox_inches="tight")
    
  • automatically adjusting the subplot params
    A way to automatically adjust the subplot position such that the legend fits inside the canvas without changing the figure size can be found in this answer: Creating figure with exact size and no padding (and legend outside the axes)

Comparison between the cases discussed above:

Alternatives

A figure legend
One may use a legend to the figure instead of the axes, matplotlib.figure.Figure.legend. This has become especially useful for matplotlib version >=2.1, where no special arguments are needed

fig.legend(loc=7) 

to create a legend for all artists in the different axes of the figure. The legend is placed using the loc argument, similar to how it is placed inside an axes, but in reference to the whole figure – hence it will be outside the axes somewhat automatically. What remains is to adjust the subplots such that there is no overlap between the legend and the axes. Here the point “Adjust the subplot parameters” from above will be helpful. An example:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,2*np.pi)
colors=["#7aa0c4","#ca82e1" ,"#8bcd50","#e18882"]
fig, axes = plt.subplots(ncols=2)
for i in range(4):
    axes[i//2].plot(x,np.sin(x+i), color=colors[i],label="y=sin(x+{})".format(i))

fig.legend(loc=7)
fig.tight_layout()
fig.subplots_adjust(right=0.75)   
plt.show()

Legend inside dedicated subplot axes
An alternative to using bbox_to_anchor would be to place the legend in its dedicated subplot axes (lax). Since the legend subplot should be smaller than the plot, we may use gridspec_kw={"width_ratios":[4,1]} at axes creation. We can hide the axes lax.axis("off") but still put a legend in. The legend handles and labels need to obtained from the real plot via h,l = ax.get_legend_handles_labels(), and can then be supplied to the legend in the lax subplot, lax.legend(h,l). A complete example is below.

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = 6,2

fig, (ax,lax) = plt.subplots(ncols=2, gridspec_kw={"width_ratios":[4,1]})
ax.plot(x,y, label="y=sin(x)")
....

h,l = ax.get_legend_handles_labels()
lax.legend(h,l, borderaxespad=0)
lax.axis("off")

plt.tight_layout()
plt.show()

This produces a plot which is visually pretty similar to the plot from above:

We could also use the first axes to place the legend, but use the bbox_transform of the legend axes,

ax.legend(bbox_to_anchor=(0,0,1,1), bbox_transform=lax.transAxes)
lax.axis("off")

In this approach, we do not need to obtain the legend handles externally, but we need to specify the bbox_to_anchor argument.

Further reading and notes:

  • Consider the matplotlib legend guide with some examples of other stuff you want to do with legends.
  • Some example code for placing legends for pie charts may directly be found in answer to this question: Python – Legend overlaps with the pie chart
  • The loc argument can take numbers instead of strings, which make calls shorter, however, they are not very intuitively mapped to each other. Here is the mapping for reference:


回答 3

只需拨打legend()该电话后,plot()像这样的电话:

# matplotlib
plt.plot(...)
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))

# Pandas
df.myCol.plot().legend(loc='center left', bbox_to_anchor=(1, 0.5))

结果看起来像这样:

Just call legend() call after the plot() call like this:

# matplotlib
plt.plot(...)
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))

# Pandas
df.myCol.plot().legend(loc='center left', bbox_to_anchor=(1, 0.5))

Results would look something like this:


回答 4

要将图例放置在绘图区域之外,请使用loc和的bbox_to_anchor关键字legend()。例如,以下代码将图例放置在绘图区域的右侧:

legend(loc="upper left", bbox_to_anchor=(1,1))

有关更多信息,请参见图例指南

To place the legend outside the plot area, use loc and bbox_to_anchor keywords of legend(). For example, the following code will place the legend to the right of the plot area:

legend(loc="upper left", bbox_to_anchor=(1,1))

For more info, see the legend guide


回答 5

简短的答案:您可以使用bbox_to_anchor+ bbox_extra_artists+ bbox_inches='tight'


更长的答案:bbox_to_anchor正如其他人在答案中指出的那样,您可以用来手动指定图例框的位置。

但是,通常的问题是图例框被裁剪,例如:

import matplotlib.pyplot as plt

# data 
all_x = [10,20,30]
all_y = [[1,3], [1.5,2.9],[3,2]]

# Plot
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(all_x, all_y)

# Add legend, title and axis labels
lgd = ax.legend( [ 'Lag ' + str(lag) for lag in all_x], loc='center right', bbox_to_anchor=(1.3, 0.5))
ax.set_title('Title')
ax.set_xlabel('x label')
ax.set_ylabel('y label')

fig.savefig('image_output.png', dpi=300, format='png')

为了防止图例框被裁剪,在保存图形时,可以使用参数bbox_extra_artistsbbox_inches要求savefig在保存的图像中包括裁剪的元素:

fig.savefig('image_output.png', bbox_extra_artists=(lgd,), bbox_inches='tight')

示例(我只更改了最后一行,向添加了2个参数fig.savefig()):

import matplotlib.pyplot as plt

# data 
all_x = [10,20,30]
all_y = [[1,3], [1.5,2.9],[3,2]]

# Plot
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(all_x, all_y)

# Add legend, title and axis labels
lgd = ax.legend( [ 'Lag ' + str(lag) for lag in all_x], loc='center right', bbox_to_anchor=(1.3, 0.5))
ax.set_title('Title')
ax.set_xlabel('x label')
ax.set_ylabel('y label')    

fig.savefig('image_output.png', dpi=300, format='png', bbox_extra_artists=(lgd,), bbox_inches='tight')

我希望matplotlib像Matlab一样本机地允许图例框位于外部位置:

figure
x = 0:.2:12;
plot(x,besselj(1,x),x,besselj(2,x),x,besselj(3,x));
hleg = legend('First','Second','Third',...
              'Location','NorthEastOutside')
% Make the text of the legend italic and color it brown
set(hleg,'FontAngle','italic','TextColor',[.3,.2,.1])

Short answer: you can use bbox_to_anchor + bbox_extra_artists + bbox_inches='tight'.


Longer answer: You can use bbox_to_anchor to manually specify the location of the legend box, as some other people have pointed out in the answers.

However, the usual issue is that the legend box is cropped, e.g.:

import matplotlib.pyplot as plt

# data 
all_x = [10,20,30]
all_y = [[1,3], [1.5,2.9],[3,2]]

# Plot
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(all_x, all_y)

# Add legend, title and axis labels
lgd = ax.legend( [ 'Lag ' + str(lag) for lag in all_x], loc='center right', bbox_to_anchor=(1.3, 0.5))
ax.set_title('Title')
ax.set_xlabel('x label')
ax.set_ylabel('y label')

fig.savefig('image_output.png', dpi=300, format='png')

In order to prevent the legend box from getting cropped, when you save the figure you can use the parameters bbox_extra_artists and bbox_inches to ask savefig to include cropped elements in the saved image:

fig.savefig('image_output.png', bbox_extra_artists=(lgd,), bbox_inches='tight')

Example (I only changed the last line to add 2 parameters to fig.savefig()):

import matplotlib.pyplot as plt

# data 
all_x = [10,20,30]
all_y = [[1,3], [1.5,2.9],[3,2]]

# Plot
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(all_x, all_y)

# Add legend, title and axis labels
lgd = ax.legend( [ 'Lag ' + str(lag) for lag in all_x], loc='center right', bbox_to_anchor=(1.3, 0.5))
ax.set_title('Title')
ax.set_xlabel('x label')
ax.set_ylabel('y label')    

fig.savefig('image_output.png', dpi=300, format='png', bbox_extra_artists=(lgd,), bbox_inches='tight')

I wish that matplotlib would natively allow outside location for the legend box as Matlab does:

figure
x = 0:.2:12;
plot(x,besselj(1,x),x,besselj(2,x),x,besselj(3,x));
hleg = legend('First','Second','Third',...
              'Location','NorthEastOutside')
% Make the text of the legend italic and color it brown
set(hleg,'FontAngle','italic','TextColor',[.3,.2,.1])


回答 6

除了此处所有出色的答案外,如果可能,较新版本的matplotlibpylab可以自动确定放置图例的位置而不会干扰绘图

pylab.legend(loc='best')

如果可能,这将自动使图例远离数据!

但是,如果没有地方放置图例而不重叠数据,那么您将要尝试其他答案之一。使用loc="best"绝不会将图例放在情节之外

In addition to all the excellent answers here, newer versions of matplotlib and pylab can automatically determine where to put the legend without interfering with the plots, if possible.

pylab.legend(loc='best')

This will automatically place the legend away from the data if possible!

However, if there is no place to put the legend without overlapping the data, then you’ll want to try one of the other answers; using loc="best" will never put the legend outside of the plot.


回答 7

简短答案:调用图例上的可拖动对象,并将其交互式移动到所需位置:

ax.legend().draggable()

长答案:如果您希望以交互/手动方式而不是通过编程方式放置图例,则可以切换图例的可拖动模式,以便将其拖到所需的位置。检查以下示例:

import matplotlib.pylab as plt
import numpy as np
#define the figure and get an axes instance
fig = plt.figure()
ax = fig.add_subplot(111)
#plot the data
x = np.arange(-5, 6)
ax.plot(x, x*x, label='y = x^2')
ax.plot(x, x*x*x, label='y = x^3')
ax.legend().draggable()
plt.show()

Short Answer: Invoke draggable on the legend and interactively move it wherever you want:

ax.legend().draggable()

Long Answer: If you rather prefer to place the legend interactively/manually rather than programmatically, you can toggle the draggable mode of the legend so that you can drag it to wherever you want. Check the example below:

import matplotlib.pylab as plt
import numpy as np
#define the figure and get an axes instance
fig = plt.figure()
ax = fig.add_subplot(111)
#plot the data
x = np.arange(-5, 6)
ax.plot(x, x*x, label='y = x^2')
ax.plot(x, x*x*x, label='y = x^3')
ax.legend().draggable()
plt.show()

回答 8

并非完全符合您的要求,但我发现它可以替代同一问题。使图例半透明,如下所示:

使用以下方法执行此操作:

fig = pylab.figure()
ax = fig.add_subplot(111)
ax.plot(x,y,label=label,color=color)
# Make the legend transparent:
ax.legend(loc=2,fontsize=10,fancybox=True).get_frame().set_alpha(0.5)
# Make a transparent text box
ax.text(0.02,0.02,yourstring, verticalalignment='bottom',
                     horizontalalignment='left',
                     fontsize=10,
                     bbox={'facecolor':'white', 'alpha':0.6, 'pad':10},
                     transform=self.ax.transAxes)

Not exactly what you asked for, but I found it’s an alternative for the same problem. Make the legend semi-transparant, like so:

Do this with:

fig = pylab.figure()
ax = fig.add_subplot(111)
ax.plot(x,y,label=label,color=color)
# Make the legend transparent:
ax.legend(loc=2,fontsize=10,fancybox=True).get_frame().set_alpha(0.5)
# Make a transparent text box
ax.text(0.02,0.02,yourstring, verticalalignment='bottom',
                     horizontalalignment='left',
                     fontsize=10,
                     bbox={'facecolor':'white', 'alpha':0.6, 'pad':10},
                     transform=self.ax.transAxes)

回答 9

如前所述,您还可以将图例放置在图中,或者也可以略微移到边缘。这是一个使用IPython Notebook制作的Plotly Python API的示例。我在团队中。

首先,您需要安装必要的软件包:

import plotly
import math
import random
import numpy as np

然后,安装Plotly:

un='IPython.Demo'
k='1fw3zw2o13'
py = plotly.plotly(username=un, key=k)


def sin(x,n):
sine = 0
for i in range(n):
    sign = (-1)**i
    sine = sine + ((x**(2.0*i+1))/math.factorial(2*i+1))*sign
return sine

x = np.arange(-12,12,0.1)

anno = {
'text': '$\\sum_{k=0}^{\\infty} \\frac {(-1)^k x^{1+2k}}{(1 + 2k)!}$',
'x': 0.3, 'y': 0.6,'xref': "paper", 'yref': "paper",'showarrow': False,
'font':{'size':24}
}

l = {
'annotations': [anno], 
'title': 'Taylor series of sine',
'xaxis':{'ticks':'','linecolor':'white','showgrid':False,'zeroline':False},
'yaxis':{'ticks':'','linecolor':'white','showgrid':False,'zeroline':False},
'legend':{'font':{'size':16},'bordercolor':'white','bgcolor':'#fcfcfc'}
}

py.iplot([{'x':x, 'y':sin(x,1), 'line':{'color':'#e377c2'}, 'name':'$x\\\\$'},\
      {'x':x, 'y':sin(x,2), 'line':{'color':'#7f7f7f'},'name':'$ x-\\frac{x^3}{6}$'},\
      {'x':x, 'y':sin(x,3), 'line':{'color':'#bcbd22'},'name':'$ x-\\frac{x^3}{6}+\\frac{x^5}{120}$'},\
      {'x':x, 'y':sin(x,4), 'line':{'color':'#17becf'},'name':'$ x-\\frac{x^5}{120}$'}], layout=l)

这将创建您的图形,并使您有机会将图例保留在绘图中。如未设置,图例的默认设置是将其放置在绘图中,如下所示。

对于替代放置,可以使图形的边缘与图例的边界紧密对齐,并删除边界线以使其更紧密。

您可以使用代码或GUI移动图例和图形并重新设置其样式。要移动图例,您可以使用以下选项通过指定x和y值<= 1来将图例放置在图形中。例如:

  • {"x" : 0,"y" : 0} – 左下方
  • {"x" : 1, "y" : 0} -右下
  • {"x" : 1, "y" : 1} – 右上
  • {"x" : 0, "y" : 1} – 左上方
  • {"x" :.5, "y" : 0} -底部中心
  • {"x": .5, "y" : 1} -顶尖中心

在这种情况下,我们选择右上角的legendstyle = {"x" : 1, "y" : 1},也在文档中进行了描述

As noted, you could also place the legend in the plot, or slightly off it to the edge as well. Here is an example using the Plotly Python API, made with an IPython Notebook. I’m on the team.

To begin, you’ll want to install the necessary packages:

import plotly
import math
import random
import numpy as np

Then, install Plotly:

un='IPython.Demo'
k='1fw3zw2o13'
py = plotly.plotly(username=un, key=k)


def sin(x,n):
sine = 0
for i in range(n):
    sign = (-1)**i
    sine = sine + ((x**(2.0*i+1))/math.factorial(2*i+1))*sign
return sine

x = np.arange(-12,12,0.1)

anno = {
'text': '$\\sum_{k=0}^{\\infty} \\frac {(-1)^k x^{1+2k}}{(1 + 2k)!}$',
'x': 0.3, 'y': 0.6,'xref': "paper", 'yref': "paper",'showarrow': False,
'font':{'size':24}
}

l = {
'annotations': [anno], 
'title': 'Taylor series of sine',
'xaxis':{'ticks':'','linecolor':'white','showgrid':False,'zeroline':False},
'yaxis':{'ticks':'','linecolor':'white','showgrid':False,'zeroline':False},
'legend':{'font':{'size':16},'bordercolor':'white','bgcolor':'#fcfcfc'}
}

py.iplot([{'x':x, 'y':sin(x,1), 'line':{'color':'#e377c2'}, 'name':'$x\\\\$'},\
      {'x':x, 'y':sin(x,2), 'line':{'color':'#7f7f7f'},'name':'$ x-\\frac{x^3}{6}$'},\
      {'x':x, 'y':sin(x,3), 'line':{'color':'#bcbd22'},'name':'$ x-\\frac{x^3}{6}+\\frac{x^5}{120}$'},\
      {'x':x, 'y':sin(x,4), 'line':{'color':'#17becf'},'name':'$ x-\\frac{x^5}{120}$'}], layout=l)

This creates your graph, and allows you a chance to keep the legend within the plot itself. The default for the legend if it is not set is to place it in the plot, as shown here.

For an alternative placement, you can closely align the edge of the graph and border of the legend, and remove border lines for a closer fit.

You can move and re-style the legend and graph with code, or with the GUI. To shift the legend, you have the following options to position the legend inside the graph by assigning x and y values of <= 1. E.g :

  • {"x" : 0,"y" : 0} — Bottom Left
  • {"x" : 1, "y" : 0} — Bottom Right
  • {"x" : 1, "y" : 1} — Top Right
  • {"x" : 0, "y" : 1} — Top Left
  • {"x" :.5, "y" : 0} — Bottom Center
  • {"x": .5, "y" : 1} — Top Center

In this case, we choose the upper right, legendstyle = {"x" : 1, "y" : 1}, also described in the documentation:


回答 10

这些方针对我有用。从Joe的一些代码开始,此方法修改了窗口的宽度,以自动适应图右边的图例。

import matplotlib.pyplot as plt
import numpy as np

plt.ion()

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$'%i)

# Put a legend to the right of the current axis
leg = ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

plt.draw()

# Get the ax dimensions.
box = ax.get_position()
xlocs = (box.x0,box.x1)
ylocs = (box.y0,box.y1)

# Get the figure size in inches and the dpi.
w, h = fig.get_size_inches()
dpi = fig.get_dpi()

# Get the legend size, calculate new window width and change the figure size.
legWidth = leg.get_window_extent().width
winWidthNew = w*dpi+legWidth
fig.set_size_inches(winWidthNew/dpi,h)

# Adjust the window size to fit the figure.
mgr = plt.get_current_fig_manager()
mgr.window.wm_geometry("%ix%i"%(winWidthNew,mgr.window.winfo_height()))

# Rescale the ax to keep its original size.
factor = w*dpi/winWidthNew
x0 = xlocs[0]*factor
x1 = xlocs[1]*factor
width = box.width*factor
ax.set_position([x0,ylocs[0],x1-x0,ylocs[1]-ylocs[0]])

plt.draw()

Something along these lines worked for me. Starting with a bit of code taken from Joe, this method modifies the window width to automatically fit a legend to the right of the figure.

import matplotlib.pyplot as plt
import numpy as np

plt.ion()

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$'%i)

# Put a legend to the right of the current axis
leg = ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

plt.draw()

# Get the ax dimensions.
box = ax.get_position()
xlocs = (box.x0,box.x1)
ylocs = (box.y0,box.y1)

# Get the figure size in inches and the dpi.
w, h = fig.get_size_inches()
dpi = fig.get_dpi()

# Get the legend size, calculate new window width and change the figure size.
legWidth = leg.get_window_extent().width
winWidthNew = w*dpi+legWidth
fig.set_size_inches(winWidthNew/dpi,h)

# Adjust the window size to fit the figure.
mgr = plt.get_current_fig_manager()
mgr.window.wm_geometry("%ix%i"%(winWidthNew,mgr.window.winfo_height()))

# Rescale the ax to keep its original size.
factor = w*dpi/winWidthNew
x0 = xlocs[0]*factor
x1 = xlocs[1]*factor
width = box.width*factor
ax.set_position([x0,ylocs[0],x1-x0,ylocs[1]-ylocs[0]])

plt.draw()

回答 11

值得刷新这个问题,因为较新版本的Matplotlib使得将图例放置在图外更加容易。我用Matplotlib版本制作了这个例子3.1.1

用户可以将2元组的坐标传递给loc参数,以将图例放置在边界框中的任何位置。唯一的难题是您需要运行plt.tight_layout()matplotlib来重新计算绘图尺寸,以便图例可见:

import matplotlib.pyplot as plt

plt.plot([0, 1], [0, 1], label="Label 1")
plt.plot([0, 1], [0, 2], label='Label 2')

plt.legend(loc=(1.05, 0.5))
plt.tight_layout()

这导致以下图:

参考文献:

It’s worth refreshing this question, as newer versions of Matplotlib have made it much easier to position the legend outside the plot. I produced this example with Matplotlib version 3.1.1.

Users can pass a 2-tuple of coordinates to the loc parameter to position the legend anywhere in the bounding box. The only gotcha is you need to run plt.tight_layout() to get matplotlib to recompute the plot dimensions so the legend is visible:

import matplotlib.pyplot as plt

plt.plot([0, 1], [0, 1], label="Label 1")
plt.plot([0, 1], [0, 2], label='Label 2')

plt.legend(loc=(1.05, 0.5))
plt.tight_layout()

This leads to the following plot:

References:


回答 12

您也可以尝试figlegend。可以创建独立于任何轴对象的图例。但是,您可能需要创建一些“虚拟”路径,以确保正确传递对象的格式。

You can also try figlegend. It is possible to create a legend independent of any Axes object. However, you may need to create some “dummy” Paths to make sure the formatting for the objects gets passed on correctly.


回答 13

这是来自matplotlib教程的示例,可在此处找到。这是更简单的示例之一,但是我为图例添加了透明度,并添加了plt.show(),因此您可以将其粘贴到交互式外壳中并获得结果:

import matplotlib.pyplot as plt
p1, = plt.plot([1, 2, 3])
p2, = plt.plot([3, 2, 1])
p3, = plt.plot([2, 3, 1])
plt.legend([p2, p1, p3], ["line 1", "line 2", "line 3"]).get_frame().set_alpha(0.5)
plt.show()

Here is an example from the matplotlib tutorial found here. This is one of the more simpler examples but I added transparency to the legend and added plt.show() so you can paste this into the interactive shell and get a result:

import matplotlib.pyplot as plt
p1, = plt.plot([1, 2, 3])
p2, = plt.plot([3, 2, 1])
p3, = plt.plot([2, 3, 1])
plt.legend([p2, p1, p3], ["line 1", "line 2", "line 3"]).get_frame().set_alpha(0.5)
plt.show()

回答 14

当我拥有传奇人物时,对我有用的解决方案是使用额外的空白图像布局。在下面的示例中,我制作了4行,在底部绘制了带有图例偏​​移(bbox_to_anchor)的图像,在顶部没有剪切。

f = plt.figure()
ax = f.add_subplot(414)
lgd = ax.legend(loc='upper left', bbox_to_anchor=(0, 4), mode="expand", borderaxespad=0.3)
ax.autoscale_view()
plt.savefig(fig_name, format='svg', dpi=1200, bbox_extra_artists=(lgd,), bbox_inches='tight')

The solution that worked for me when I had huge legend was to use extra empty image layout. In following example I made 4 rows and at the bottom I plot image with offset for legend (bbox_to_anchor) at the top it does not get cut.

f = plt.figure()
ax = f.add_subplot(414)
lgd = ax.legend(loc='upper left', bbox_to_anchor=(0, 4), mode="expand", borderaxespad=0.3)
ax.autoscale_view()
plt.savefig(fig_name, format='svg', dpi=1200, bbox_extra_artists=(lgd,), bbox_inches='tight')

回答 15

这是另一种解决方案,类似于添加bbox_extra_artistsbbox_inches,您不必在savefig通话范围内增加额外的演出者。我想出了这个,因为我在函数中生成了大部分图。

无需将所有添加内容添加到边框中,就可以提前将其添加到Figure的艺术家中。使用类似于弗朗克·德农库尔(Franck Dernoncourt)的上述答案

import matplotlib.pyplot as plt

# data 
all_x = [10,20,30]
all_y = [[1,3], [1.5,2.9],[3,2]]

# plotting function
def gen_plot(x, y):
    fig = plt.figure(1)
    ax = fig.add_subplot(111)
    ax.plot(all_x, all_y)
    lgd = ax.legend( [ "Lag " + str(lag) for lag in all_x], loc="center right", bbox_to_anchor=(1.3, 0.5))
    fig.artists.append(lgd) # Here's the change
    ax.set_title("Title")
    ax.set_xlabel("x label")
    ax.set_ylabel("y label")
    return fig

# plotting
fig = gen_plot(all_x, all_y)

# No need for `bbox_extra_artists`
fig.savefig("image_output.png", dpi=300, format="png", bbox_inches="tight")

这是生成的图。

Here’s another solution, similar to adding bbox_extra_artists and bbox_inches, where you don’t have to have your extra artists in the scope of your savefig call. I came up with this since I generate most of my plot inside functions.

Instead of adding all your additions to the bounding box when you want to write it out, you can add them ahead of time to the Figure‘s artists. Using something similar to Franck Dernoncourt’s answer above:

import matplotlib.pyplot as plt

# data 
all_x = [10,20,30]
all_y = [[1,3], [1.5,2.9],[3,2]]

# plotting function
def gen_plot(x, y):
    fig = plt.figure(1)
    ax = fig.add_subplot(111)
    ax.plot(all_x, all_y)
    lgd = ax.legend( [ "Lag " + str(lag) for lag in all_x], loc="center right", bbox_to_anchor=(1.3, 0.5))
    fig.artists.append(lgd) # Here's the change
    ax.set_title("Title")
    ax.set_xlabel("x label")
    ax.set_ylabel("y label")
    return fig

# plotting
fig = gen_plot(all_x, all_y)

# No need for `bbox_extra_artists`
fig.savefig("image_output.png", dpi=300, format="png", bbox_inches="tight")

Here’s the generated plot.


回答 16

不知道您是否已经解决了问题……可能是的,但是……我只是使用字符串“ outside”作为位置,例如在matlab中。我从matplotlib导入pylab。请参见以下代码:

from matplotlib as plt
from matplotlib.font_manager import FontProperties
...
...
t = A[:,0]
sensors = A[:,index_lst]

for i in range(sensors.shape[1]):
    plt.plot(t,sensors[:,i])

plt.xlabel('s')
plt.ylabel('°C')
lgd = plt.legend(b,loc='center left', bbox_to_anchor=(1, 0.5),fancybox = True, shadow = True)

点击查看剧情

don’t know if you already sorted out your issue…probably yes, but… I simply used the string ‘outside’ for the location, like in matlab. I imported pylab from matplotlib. see the code as follow:

from matplotlib as plt
from matplotlib.font_manager import FontProperties
...
...
t = A[:,0]
sensors = A[:,index_lst]

for i in range(sensors.shape[1]):
    plt.plot(t,sensors[:,i])

plt.xlabel('s')
plt.ylabel('°C')
lgd = plt.legend(b,loc='center left', bbox_to_anchor=(1, 0.5),fancybox = True, shadow = True)

Click to see the plot


Mlcourse.ai-开放机器学习课程

mlcourse.ai是一门开放的机器学习课程,由OpenDataScience (ods.ai),由Yury Kashnitsky (yorko)尤里拥有应用数学博士学位和卡格尔竞赛大师学位,他的目标是设计一门理论与实践完美平衡的ML课程。因此,你可以在课堂上复习数学公式,并与Kaggle Inclass竞赛一起练习。目前,该课程正处于自定步模式检查一下详细的Roadmap引导您完成自定进度的课程。ai

奖金:此外,您还可以购买带有最佳非演示版本的奖励作业包mlcourse.ai任务。选择“Bonus Assignments” tier请参阅主页上的交易详情mlcourse.ai

镜子(🇬🇧-仅限):mlcourse.ai(主站点)、Kaggle Dataset(与Kaggle笔记本相同的笔记本)

自定

这个Roadmap将指导您度过11周的mlCourse.ai课程。每周,从熊猫到梯度助推,都会给出阅读什么文章、看什么讲座、完成什么作业的指示。

内容

这是medium.com上发表的文章列表🇬🇧,habr.com🇷🇺还提到了中文笔记本。🇨🇳并给出了指向Kaggle笔记本(英文)的链接。图标是可点击的

  1. 用PANDA软件进行探索性数据分析🇬🇧🇷🇺🇨🇳Kaggle Notebook
  2. 用Python进行可视化数据分析🇬🇧🇷🇺🇨🇳,Kaggle笔记本电脑:part1part2
  3. 分类、决策树和k近邻🇬🇧🇷🇺🇨🇳Kaggle Notebook
  4. 线性分类与回归🇬🇧🇷🇺🇨🇳,Kaggle笔记本电脑:part1part2part3part4part5
  5. 套袋与随机林🇬🇧🇷🇺🇨🇳,Kaggle笔记本电脑:part1part2part3
  6. 特征工程与特征选择🇬🇧🇷🇺🇨🇳Kaggle Notebook
  7. 无监督学习:主成分分析与聚类🇬🇧🇷🇺🇨🇳Kaggle Notebook
  8. Vowpal Wabbit:用千兆字节的数据学习🇬🇧🇷🇺🇨🇳Kaggle Notebook
  9. 用Python进行时间序列分析,第一部分🇬🇧🇷🇺🇨🇳使用Facebook Prophet预测未来,第2部分🇬🇧🇨🇳卡格尔笔记本:part1part2
  10. 梯度增压🇬🇧🇷🇺🇨🇳Kaggle Notebook

讲座

视频上传到thisYouTube播放列表。引言,videoslides

  1. 用熊猫进行探索性数据分析,video
  2. 可视化,EDA的主要情节,video
  3. 诊断树:theorypractical part
  4. Logistic回归:theoretical foundationspractical part(《爱丽丝》比赛中的基线)
  5. 合奏和随机森林-part 1分类指标-part 2预测客户付款的业务任务示例-part 3
  6. 线性回归和正则化-theory,Lasso&Ridge,LTV预测-practice
  7. 无监督学习-Principal Component AnalysisClustering
  8. 用于分类和回归的随机梯度下降-part 1,第2部分TBA
  9. 用Python(ARIMA,PERPHET)进行时间序列分析-video
  10. 梯度增压:基本思路-part 1、XgBoost、LightGBM和CatBoost+Practice背后的关键理念-part 2

作业

以下是演示作业。此外,在“Bonus Assignments” tier您可以访问非演示作业

  1. 用熊猫进行探索性数据分析,nbviewerKaggle Notebooksolution
  2. 分析心血管疾病数据,nbviewerKaggle Notebooksolution
  3. 带有玩具任务和UCI成人数据集的决策树,nbviewerKaggle Notebooksolution
  4. 讽刺检测,Kaggle Notebooksolution线性回归作为一个最优化问题,nbviewerKaggle Notebook
  5. Logistic回归和随机森林在信用评分问题中的应用nbviewerKaggle Notebooksolution
  6. 在回归任务中探索OLS、LASSO和随机森林nbviewerKaggle Notebooksolution
  7. 无监督学习,nbviewerKaggle Notebooksolution
  8. 实现在线回归,nbviewerKaggle Notebooksolution
  9. 时间序列分析,nbviewerKaggle Notebooksolution
  10. 在比赛中超越底线,Kaggle Notebook

卡格尔竞赛

  1. 如果可以,请抓住我:通过网页会话跟踪检测入侵者。Kaggle Inclass
  2. Dota 2获胜者预测。Kaggle Inclass

引用mlCourse.ai

如果你碰巧引用了mlcourse.ai在您的工作中,您可以使用此BibTeX记录:

@misc{mlcourse_ai,
    author = {Kashnitsky, Yury},
    title = {mlcourse.ai – Open Machine Learning Course},
    year = {2020},
    publisher = {GitHub},
    journal = {GitHub repository},
    howpublished = {\url{https://github.com/Yorko/mlcourse.ai}},
}

社区

讨论在#mlCourse_ai世界上最重要的一条航道OpenDataScience (ods.ai)松懈团队

课程是免费的,但你可以通过承诺以下内容来支持组织者Patreon(每月支持)或一次性付款Ko-fi


Matplotlib:使用Python绘图

Matplotlib是一个综合性的库,用于用Python语言创建静电、动画和交互式可视化效果

请查看我们的home page了解更多信息

Matplotlib以各种硬拷贝格式和跨平台的交互环境制作出版质量的数字。Matplotlib可用于Python脚本、Python和IPython shell、Web应用程序服务器以及各种图形用户界面工具包

安装

有关安装说明和要求,请参见INSTALL.rst或者install文档

测试

安装后,启动测试套件:

python -m pytest

请阅读testing guide有关更多信息和替代方案

贡献力量

您发现了一个bug或其他您想要更改的东西-太棒了!

你已经想出了一种修复它的方法–甚至更好!

你想告诉我们这件事–最棒的是!

contributing guide好了!

联系方式

Discourse是一般性问题和讨论的讨论论坛,也是我们推荐的起点。

我们的活动邮件列表(反映在话语中)是:

Gitter用于协调发展并提出与matplotlib直接相关的问题

引用Matplotlib

如果Matplotlib对导致出版的项目做出了贡献,请引用Matplotlib来确认这一点

A ready-made citation entry有空房吗?

研究通知

请注意,该存储库正在参与一项关于开放源码项目可持续性的研究。从2021年6月开始,将在大约12个月的时间内收集有关此存储库的数据

收集的数据将包括贡献者数量、PR数量、关闭/合并这些PR所需的时间以及已关闭的问题

欲了解更多信息,请访问the informational
page
或下载participant information
sheet

Data-science-ipython-notebooks-数据科学Python笔记本:深度学习

数据-科学-IPython-笔记本

索引

深度学习

演示深度学习功能的IPython笔记本

张量流教程

其他TensorFlow教程:

笔记本电脑 描述
tsf-basics 在TensorFlow中学习基本操作,TensorFlow是Google提供的各种感知和语言理解任务的库
tsf-linear 在TensorFlow中实现线性回归
tsf-logistic 在TensorFlow中实现Logistic回归
tsf-nn 在TensorFlow中实现最近邻居
tsf-alex 在TensorFlow中实现AlexNet
tsf-cnn 卷积神经网络在TensorFlow中的实现
tsf-mlp 在TensorFlow中实现多层感知器
tsf-rnn 递归神经网络在TensorFlow中的实现
tsf-gpu 了解TensorFlow中的基本多GPU计算
tsf-gviz 了解TensorFlow中的图形可视化
tsf-lviz 了解TensorFlow中的损耗可视化

张量流练习

笔记本电脑 描述
tsf-not-mnist 通过为TensorFlow中的培训、开发和测试创建带有格式化数据集的Pickle,了解简单的数据管理
tsf-fully-connected 在TensorFlow中使用Logistic回归和神经网络逐步训练更深更精确的模型
tsf-regularization 通过训练全连通网络对TensorFlow中的notMNIST字符进行分类来探索正则化技术
tsf-convolutions 在TensorFlow中创建卷积神经网络
tsf-word2vec 在TensorFlow中对Text8数据训练跳格模型
tsf-lstm 在TensorFlow中对Text8数据训练LSTM字符模型

Theano-教程

笔记本电脑 描述
theano-intro Theano简介,它允许您高效地定义、优化和计算涉及多维数组的数学表达式。它可以使用GPU并执行高效的符号微分
theano-scan 学习扫描,这是一种在Theano图中执行循环的机制
theano-logistic 在Theano中实现Logistic回归
theano-rnn 递归神经网络在Theano中的实现
theano-mlp 在Theano中实现多层感知器

Keras-教程

笔记本电脑 描述
角膜 KERAS是一个用Python编写的开源神经网络库。它可以在TensorFlow或Theano上运行
setup 了解教程目标以及如何设置Kera环境
intro-deep-learning-ann 介绍使用KERAS和人工神经网络(ANN)进行深度学习
theano 通过使用权重矩阵和梯度了解Theano
keras-otto 通过观看卡格尔·奥托挑战赛了解凯拉斯
ann-mnist 基于KERAS的MNIST人工神经网络的简单实现
conv-nets 使用KERAS了解卷积神经网络(CNN)
conv-net-1 使用KERA识别MNIST中的手写数字-第1部分
conv-net-2 使用KERA识别MNIST中的手写数字-第2部分
keras-models 将预先培训的型号(如VGG16、VGG19、ResNet50和Inception v3)与KERA配合使用
auto-encoders 了解有关KERAS自动编码器的信息
rnn-lstm 使用KERAS了解递归神经网络(RNN)
lstm-sentence-gen 了解与KERA配合使用长短期内存(LSTM)网络的RNN

深度学习-其他

笔记本电脑 描述
deep-dream 基于Caffe的计算机视觉程序,使用卷积神经网络来查找和增强图像中的图案

科学工具包-学习

演示SCRICKIT学习功能的IPython笔记本

笔记本电脑 描述
intro 介绍笔记本到SCRICKIT-学习。Scikit-Learning添加了对大型多维数组和矩阵的Python支持,以及对这些数组进行操作的高级数学函数库的大型库
knn 在SCRICKIT-LEARN中实现k-近邻
linear-reg 在SCRICKIT-LEARCH中实现线性回归
svm 在SCRKIT-LEARN中实现带核和不带核的支持向量机分类器
random-forest 在SCRICKIT-LEARN中实现随机森林分类器和回归器
k-means 在SCRICIT-LEARN中实现k-均值聚类
pca 主成分分析在SCRICIT-LEARCH中的实现
gmm 在SCRICIT-LEARN中实现高斯混合模型
validation 在SCRICKIT-LEARN中实现验证和模型选择

统计推理法

演示使用SciPy功能进行统计推断的IPython笔记本

笔记本电脑 描述
尖刺的 SciPy是构建在Python的Numpy扩展上的数学算法和便利函数的集合。它为用户提供用于操作和可视化数据的高级命令和类,从而大大增强了交互式Python会话的功能
effect-size 通过分析男性和女性的身高差异,探索量化效应大小的统计数据。使用行为危险因素监测系统(BRFSS)的数据来估计美国成年女性和男性的平均身高和标准偏差
sampling 利用BRFSS数据分析美国男女平均体重探索随机抽样
hypothesis 通过分析头胎婴儿与其他婴儿的差异来探索假设检验

熊猫

演示熊猫功能的IPython笔记本

笔记本电脑 描述
pandas 用Python编写的用于数据操作和分析的软件库。提供用于操作数值表和时间序列的数据结构和操作
github-data-wrangling 通过分析中的GitHub数据,了解如何加载、清理、合并和要素工程Viz回购
Introduction-to-Pandas 熊猫简介
Introducing-Pandas-Objects 了解熊猫对象
Data Indexing and Selection 了解有关熊猫中的数据索引和选择的信息
Operations-in-Pandas 了解有关在熊猫中操作数据的信息
Missing-Values 了解有关处理熊猫中丢失的数据的信息
Hierarchical-Indexing 了解有关熊猫中的分层索引的信息
Concat-And-Append 了解有关组合数据集的信息:在熊猫中合并和追加
Merge-and-Join 了解有关组合数据集的信息:在熊猫中合并和连接
Aggregation-and-Grouping 了解有关在熊猫中聚合和分组的信息
Pivot-Tables 了解有关熊猫中的透视表的信息
Working-With-Strings 了解有关熊猫中的矢量化字符串操作的信息
Working-with-Time-Series 了解有关在熊猫中使用时间序列的信息
Performance-Eval-and-Query 了解高性能熊猫:熊猫中的eval()和query()

Matplotlib

演示matplotlib功能的IPython笔记本

笔记本电脑 描述
matplotlib Python 2D绘图库,以各种硬拷贝格式和跨平台交互环境生成出版物质量数据
matplotlib-applied 将matplotlib可视化应用于Kaggle比赛以进行探索性数据分析。了解如何创建条形图、直方图、子图2格网、归一化图、散点图、子图和核密度估计图
Introduction-To-Matplotlib Matplotlib简介
Simple-Line-Plots 了解有关Matplotlib中的简单线条图的信息
Simple-Scatter-Plots 了解有关Matplotlib中的简单散点图的信息
Errorbars.ipynb 了解有关在Matplotlib中可视化错误的信息
Density-and-Contour-Plots 了解Matplotlib中的密度和等高线绘图
Histograms-and-Binnings 了解有关Matplotlib中的直方图、二进制和密度的信息
Customizing-Legends 了解有关在Matplotlib中自定义地块图例的信息
Customizing-Colorbars 了解有关在Matplotlib中自定义色带的信息
Multiple-Subplots 了解有关Matplotlib中的多个子图的信息
Text-and-Annotation 了解有关Matplotlib中的文本和注记的信息
Customizing-Ticks 了解有关在Matplotlib中自定义刻度的信息
Settings-and-Stylesheets 了解有关自定义Matplotlib的信息:配置和样式表
Three-Dimensional-Plotting 了解有关在Matplotlib中进行三维打印的信息
Geographic-Data-With-Basemap 了解有关在Matplotlib中使用底图的地理数据的信息
Visualization-With-Seaborn 了解有关海运可视化的信息

麻木的

演示NumPy功能的IPython笔记本

笔记本电脑 描述
numpy 添加了对大型多维数组和矩阵的Python支持,以及对这些数组进行运算的大型高级数学函数库
Introduction-to-NumPy NumPy简介
Understanding-Data-Types 了解有关Python中的数据类型的信息
The-Basics-Of-NumPy-Arrays 了解NumPy阵列的基础知识
Computation-on-arrays-ufuncs 了解有关NumPy数组的计算:泛函
Computation-on-arrays-aggregates 了解有关聚合的信息:NumPy中的最小值、最大值以及介于两者之间的所有内容
Computation-on-arrays-broadcasting 了解有关数组计算的信息:在NumPy中广播
Boolean-Arrays-and-Masks 了解有关NumPy中的比较、掩码和布尔逻辑的信息
Fancy-Indexing 了解NumPy中的奇特索引
Sorting 了解有关在NumPy中对数组进行排序的信息
Structured-Data-NumPy 了解结构化数据:NumPy的结构化数组

Python-Data

IPython笔记本,演示面向数据分析的Python功能

笔记本电脑 描述
data structures 使用元组、列表、字典、集学习Python基础知识
data structure utilities 学习Python操作,如切片、范围、xrange、二等分、排序、排序、反转、枚举、压缩、列表理解
functions 了解更高级的Python功能:函数作为对象、lambda函数、闭包、*args、**kwargs curying、生成器、生成器表达式、itertools
datetime 了解如何使用Python日期和时间:datetime、strftime、strptime、timeDelta
logging 了解有关使用RotatingFileHandler和TimedRotatingFileHandler进行Python日志记录的信息
pdb 了解如何使用交互式源代码调试器在Python中进行调试
unit tests 了解如何在Python中使用NOSE单元测试进行测试

Kaggle-and-Business分析

中使用的IPython笔记本kaggle竞争和业务分析

笔记本电脑 描述
titanic 预测泰坦尼克号上的生还者。学习数据清理、探索性数据分析和机器学习
churn-analysis 预测客户流失。练习逻辑回归、梯度增强分类器、支持向量机、随机森林和k近邻。包括对念力矩阵、ROC图、特征重要性、预测概率和校准/识别的讨论

电光

演示电光和HDFS功能的IPython笔记本

笔记本电脑 描述
spark 内存集群计算框架,对于某些应用程序速度最高可提高100倍,并且非常适合机器学习算法
hdfs 在大型群集中跨计算机可靠地存储非常大的文件

MapReduce-Python

演示使用mrjob功能的Hadoop MapReduce的IPython笔记本

笔记本电脑 描述
mapreduce-python 在Python中运行MapReduce作业,在本地或Hadoop群集上执行作业。演示Python代码中的Hadoop流以及单元测试和mrjob用于分析Elastic MapReduce上的Amazon S3存储桶日志的配置文件。Disco是另一个基于python的替代方案。

AWS

演示Amazon Web服务(AWS)和AWS工具功能的IPython笔记本

另请查看:

  • SAWS:增强型AWS命令行界面(CLI)
  • Awesome AWS:库、开源Repos、指南、博客和其他资源的精选列表
笔记本电脑 描述
boto 针对Python的官方AWS SDK
s3cmd 通过命令行与S3交互
s3distcp 组合较小的文件,并通过接受模式和目标文件将它们聚合在一起。S3DistCp还可用于将大量数据从S3传输到您的Hadoop群集
s3-parallel-put 将多个文件并行上传到S3
redshift 充当建立在大规模并行处理(MPP)技术之上的快速数据仓库
kinesis 通过每秒处理数千个数据流的能力实时流式传输数据
lambda 运行代码以响应事件,自动管理计算资源

命令

IPython笔记本,演示Linux、Git等的各种命令行

笔记本电脑 描述
linux 类UNIX且大多兼容POSIX的计算机操作系统。磁盘使用情况、拆分文件、grep、sed、curl、查看正在运行的进程、终端语法突出显示和Vim
anaconda 发布用于大规模数据处理、预测分析和科学计算的Python编程语言,旨在简化包管理和部署
ipython notebook 基于Web的交互式计算环境,您可以在其中将代码执行、文本、数学、绘图和富媒体组合到单个文档中
git 强调速度、数据完整性并支持分布式非线性工作流的分布式修订控制系统
ruby 用于与AWS命令行和Jekyll交互,Jekyll是可托管在GitHub页面上的博客框架
jekyll 简单、支持博客的静电站点生成器,适用于个人、项目或组织站点。呈现Markdown或Textile and Liquid模板,并生成一个完整的静电网站,准备好由Apache HTTP Server、NGINX或其他Web服务器提供服务
pelican 基于Python的Jekyll替代方案
django 高级Python Web框架,鼓励快速开发和干净、实用的设计。它对共享报告/分析和博客很有用。较轻的替代方案包括PyramidFlaskTornado,以及Bottle

杂项

演示各种功能的IPython笔记本

笔记本电脑 描述
regex 数据争论中有用的正则表达式小抄
algorithmia Algorithmia是一个算法市场。本笔记本展示了4种不同的算法:人脸检测、内容摘要、潜在狄利克雷分配和光学字符识别

笔记本-安装

python

Anaconda是Python编程语言的免费发行版,用于大规模数据处理、预测分析和科学计算,旨在简化包管理和部署

按照说明进行安装Anaconda或者更轻的miniconda

设备-设置

有关设置数据分析开发环境的详细说明、脚本和工具,请参阅dev-setup回购

跑步-笔记本

要查看交互式内容或修改IPython笔记本中的元素,必须首先克隆或下载存储库,然后再运行笔记本。有关IPython笔记本的更多信息可以找到here.

$ git clone https://github.com/donnemartin/data-science-ipython-notebooks.git
$ cd data-science-ipython-notebooks
$ jupyter notebook

使用Python 2.7.x测试的笔记本电脑

学分

贡献

欢迎投稿!有关错误报告或请求,请submit an issue

联系方式-信息

请随时与我联系,讨论任何问题、问题或评论

许可证

这个存储库包含各种内容;有些是由Donne Martin开发的,有些是来自第三方的。第三方内容在这些方提供的许可下分发

由Donne Martin开发的内容按照以下许可证分发:

我在开放源码许可下向您提供此存储库中的代码和资源。因为这是我的个人存储库,您获得的我的代码和资源的许可证来自我,而不是我的雇主(Facebook)

Copyright 2015 Donne Martin

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

PythonDataScienceHandbook-Python数据科学手册:Jupyter笔记本全文

如何使用本书

关于

本书是使用Python3.5编写和测试的,尽管其他Python版本(包括Python2.7)几乎可以在所有情况下运行

本书介绍了在Python中使用数据所必需的核心库:特别是IPythonNumPyPandasMatplotlibScikit-Learn,以及相关的软件包。假设您熟悉作为一种语言的Python;如果您需要快速介绍该语言本身,请参阅免费的配套项目,A Whirlwind Tour of Python:这是一本针对研究人员和科学家的快节奏Python语言入门教程

看见Index.ipynb有关可与正文一起使用的笔记本的索引,请参阅

软件

书中的代码使用Python 3.5进行了测试,但大多数(但不是全部)也可以在Python 2.7和其他较早的Python版本中正常运行

中列出了我用来运行书中代码的包requirements.txt(请注意,其中一些确切的版本号可能在您的平台上不可用:您可能需要调整它们以供您自己使用)。要使用以下命令安装需求,请执行以下操作conda,请在命令行中运行以下命令:

$ conda install --file requirements.txt

要创建名为的独立环境,请执行以下操作PDSH对于Python 3.5和所有必需的软件包版本,请运行以下命令:

$ conda create -n PDSH python=3.5 --file requirements.txt

中可以阅读有关使用Conda环境的更多信息Managing Environments部分的CONDA文档

许可证

代码

此存储库中的代码(包括上面列出的笔记本中的所有代码示例)发布在MIT license有关更多信息,请访问Open Source Initiative

文本

这本书的正文内容在CC-BY-NC-ND license欲了解更多信息,请访问Creative Commons

PythonDataScienceHandbook-Python数据科学手册:Jupyter笔记本全文

Python Data Science Handbook

该存储库包含完整的Python数据科学手册,其形式为(免费!)Jupyter笔记本

如何使用本书

  • 请访问https://jakevdp.github.io/PythonDataScienceHandbook/在线阅读整本书
  • 使用此存储库的笔记本目录中提供的Jupyter笔记本运行代码
  • 使用Google Colab启动这些笔记本的可执行版本:
  • 使用活页夹使用以下笔记本启动实时笔记本服务器:
  • 通过O‘Reilly Media购买印刷书籍

关于

本书是使用Python3.5编写和测试的,尽管其他Python版本(包括Python2.7)几乎可以在所有情况下运行

本书介绍了在Python中使用数据所必需的核心库:特别是IPython、NumPy、Pandas、Matplotlib、Scikit-Learning和相关包。假设您熟悉Python作为一种语言;如果您需要快速介绍该语言本身,请参阅免费的配套项目-Python旋风之旅:这是针对研究人员和科学家的快速Python语言介绍

请参见Index.ipynb以获取可与文本一起使用的笔记本的索引

软件

书中的代码使用Python 3.5进行了测试,但大多数(但不是全部)也可以在Python 2.7和其他较早的Python版本中正常运行

我用来运行这本书中的代码的包列在Requirements.txt中(请注意,其中一些确切的版本号在您的平台上可能不可用:您可能必须调整它们以供您自己使用)。要使用CONDA安装需求,请在命令行运行以下命令:

$ conda install --file requirements.txt

要使用Python 3.5和所有必需的软件包版本创建名为pdsh的独立环境,请运行以下命令:

$ conda create -n PDSH python=3.5 --file requirements.txt

您可以在Conda文档的管理环境一节中阅读有关使用Conda环境的更多信息

许可证

代码

此存储库中的代码,包括上面列出的笔记本中的所有代码示例,都是在MIT许可下发布的。阅读更多关于开放源码计划的内容

文本

本书的文本内容在CC-by-NC-ND许可下发布。在知识共享网站上阅读更多内容