标签归档:seaborn

如何将Seaborn图保存到文件中

问题:如何将Seaborn图保存到文件中

我尝试了以下代码(test_seaborn.py):

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
import seaborn as sns
sns.set()
df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
fig = sns_plot.get_figure()
fig.savefig("output.png")
#sns.plt.show()

但是我得到这个错误:

  Traceback (most recent call last):
  File "test_searborn.py", line 11, in <module>
    fig = sns_plot.get_figure()
AttributeError: 'PairGrid' object has no attribute 'get_figure'

我希望决赛output.png将存在,看起来像这样:

我该如何解决该问题?

I tried the following code (test_seaborn.py):

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
import seaborn as sns
sns.set()
df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
fig = sns_plot.get_figure()
fig.savefig("output.png")
#sns.plt.show()

But I get this error:

  Traceback (most recent call last):
  File "test_searborn.py", line 11, in <module>
    fig = sns_plot.get_figure()
AttributeError: 'PairGrid' object has no attribute 'get_figure'

I expect the final output.png will exist and look like this:

How can I resolve the problem?


回答 0

删除get_figure并使用sns_plot.savefig('output.png')

df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
sns_plot.savefig("output.png")

Remove the get_figure and just use sns_plot.savefig('output.png')

df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
sns_plot.savefig("output.png")

回答 1

建议的解决方案与Seaborn 0.8.1不兼容

由于Seaborn界面已更改,因此出现以下错误:

AttributeError: 'AxesSubplot' object has no attribute 'fig'
When trying to access the figure

AttributeError: 'AxesSubplot' object has no attribute 'savefig'
when trying to use the savefig directly as a function

以下调用允许您访问该图(与Seaborn 0.8.1兼容):

swarm_plot = sns.swarmplot(...)
fig = swarm_plot.get_figure()
fig.savefig(...) 

如先前在此答案中所见。

更新: 我最近使用了seaborn的PairGrid对象生成了一个类似于本示例中的图。在这种情况下,由于GridPlot不是像sns.swarmplot这样的绘图对象,因此它没有get_figure()函数。可以通过以下方式直接访问matplotlib图

fig = myGridPlotObject.fig

就像之前在该主题的其他文章中建议的那样。

The suggested solutions are incompatible with Seaborn 0.8.1

giving the following errors because the Seaborn interface has changed:

AttributeError: 'AxesSubplot' object has no attribute 'fig'
When trying to access the figure

AttributeError: 'AxesSubplot' object has no attribute 'savefig'
when trying to use the savefig directly as a function

The following calls allow you to access the figure (Seaborn 0.8.1 compatible):

swarm_plot = sns.swarmplot(...)
fig = swarm_plot.get_figure()
fig.savefig(...) 

as seen previously in this answer.

UPDATE: I have recently used PairGrid object from seaborn to generate a plot similar to the one in this example. In this case, since GridPlot is not a plot object like, for example, sns.swarmplot, it has no get_figure() function. It is possible to directly access the matplotlib figure by

fig = myGridPlotObject.fig

Like previously suggested in other posts in this thread.


回答 2

上述某些解决方案对我不起作用。.fig尝试该属性时未找到该属性,因此无法.savefig()直接使用。但是,起作用的是:

sns_plot.figure.savefig("output.png")

我是Python新用户,所以我不知道这是否是由于更新引起的。我想提一下,以防其他人遇到和我一样的问题。

Some of the above solutions did not work for me. The .fig attribute was not found when I tried that and I was unable to use .savefig() directly. However, what did work was:

sns_plot.figure.savefig("output.png")

I am a newer Python user, so I do not know if this is due to an update. I wanted to mention it in case anybody else runs into the same issues as I did.


回答 3

您应该只能够直接使用savefig方法sns_plot

sns_plot.savefig("output.png")

为了使您的代码更加清晰,如果您确实要访问sns_plot驻留在其中的matplotlib图形,则可以直接通过

fig = sns_plot.fig

在这种情况下get_figure,您的代码将假定没有方法。

You should just be able to use the savefig method of sns_plot directly.

sns_plot.savefig("output.png")

For clarity with your code if you did want to access the matplotlib figure that sns_plot resides in then you can get it directly with

fig = sns_plot.fig

In this case there is no get_figure method as your code assumes.


回答 4

我使用distplotget_figure成功保存了图片。

sns_hist = sns.distplot(df_train['SalePrice'])
fig = sns_hist.get_figure()
fig.savefig('hist.png')

I use distplot and get_figure to save picture successfully.

sns_hist = sns.distplot(df_train['SalePrice'])
fig = sns_hist.get_figure()
fig.savefig('hist.png')

回答 5

2019年搜索者的台词更少:

import matplotlib.pyplot as plt
import seaborn as sns

df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', height=2.5)
plt.savefig('output.png')

更新说明:size已更改为height

Fewer lines for 2019 searchers:

import matplotlib.pyplot as plt
import seaborn as sns

df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', height=2.5)
plt.savefig('output.png')

UPDATE NOTE: size was changed to height.


回答 6

这对我有用

import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

sns.factorplot(x='holiday',data=data,kind='count',size=5,aspect=1)
plt.savefig('holiday-vs-count.png')

This works for me

import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

sns.factorplot(x='holiday',data=data,kind='count',size=5,aspect=1)
plt.savefig('holiday-vs-count.png')

回答 7

也可以只创建一个matplotlib figure对象,然后使用plt.savefig(...)

from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd

df = sns.load_dataset('iris')
plt.figure() # Push new figure on stack
sns_plot = sns.pairplot(df, hue='species', size=2.5)
plt.savefig('output.png') # Save that figure

Its also possible to just create a matplotlib figure object and then use plt.savefig(...):

from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd

df = sns.load_dataset('iris')
plt.figure() # Push new figure on stack
sns_plot = sns.pairplot(df, hue='species', size=2.5)
plt.savefig('output.png') # Save that figure

回答 8

sns.figure.savefig("output.png")在seaborn 0.8.1中使用会出错。

而是使用:

import seaborn as sns

df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
sns_plot.savefig("output.png")

You would get an error for using sns.figure.savefig("output.png") in seaborn 0.8.1.

Instead use:

import seaborn as sns

df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
sns_plot.savefig("output.png")

回答 9

仅供参考,下面的命令在seaborn 0.8.1中起作用,因此我想最初的答案仍然有效。

sns_plot = sns.pairplot(data, hue='species', size=3)
sns_plot.savefig("output.png")

Just FYI, the below command worked in seaborn 0.8.1 so I guess the initial answer is still valid.

sns_plot = sns.pairplot(data, hue='species', size=3)
sns_plot.savefig("output.png")

Seaborn Barplot上的标签轴

问题:Seaborn Barplot上的标签轴

我正在尝试通过以下代码将自己的标签用于Seaborn barplot:

import pandas as pd
import seaborn as sns

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', 
                  data = fake, 
                  color = 'black')
fig.set_axis_labels('Colors', 'Values')

但是,我得到一个错误:

AttributeError: 'AxesSubplot' object has no attribute 'set_axis_labels'

是什么赋予了?

I’m trying to use my own labels for a Seaborn barplot with the following code:

import pandas as pd
import seaborn as sns

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', 
                  data = fake, 
                  color = 'black')
fig.set_axis_labels('Colors', 'Values')

However, I get an error that:

AttributeError: 'AxesSubplot' object has no attribute 'set_axis_labels'

What gives?


回答 0

Seaborn的条形图返回一个轴对象(不是图形)。这意味着您可以执行以下操作:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
ax = sns.barplot(x = 'val', y = 'cat', 
              data = fake, 
              color = 'black')
ax.set(xlabel='common xlabel', ylabel='common ylabel')
plt.show()

Seaborn’s barplot returns an axis-object (not a figure). This means you can do the following:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
ax = sns.barplot(x = 'val', y = 'cat', 
              data = fake, 
              color = 'black')
ax.set(xlabel='common xlabel', ylabel='common ylabel')
plt.show()

回答 1

使用和可以避免方法AttributeError带来的麻烦。set_axis_labels()matplotlib.pyplot.xlabelmatplotlib.pyplot.ylabel

matplotlib.pyplot.xlabel设置x轴标签,而matplotlib.pyplot.ylabel设置当前轴的y轴标签。

解决方案代码:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
plt.xlabel("Colors")
plt.ylabel("Values")
plt.title("Colors vs Values") # You can comment this line out if you don't need title
plt.show(fig)

输出图:

One can avoid the AttributeError brought about by set_axis_labels() method by using the matplotlib.pyplot.xlabel and matplotlib.pyplot.ylabel.

matplotlib.pyplot.xlabel sets the x-axis label while the matplotlib.pyplot.ylabel sets the y-axis label of the current axis.

Solution code:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
plt.xlabel("Colors")
plt.ylabel("Values")
plt.title("Colors vs Values") # You can comment this line out if you don't need title
plt.show(fig)

Output figure:


回答 2

您还可以通过添加title参数来设置图表标题,如下所示

ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')

You can also set the title of your chart by adding the title parameter as follows

ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')

如何为Seaborn Facet Plot添加标题

问题:如何为Seaborn Facet Plot添加标题

如何为该海上情节添加标题?让我们给它一个标题“我是标题”。

tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col="sex", row="smoker", margin_titles=True)
g.map(sns.plt.scatter, "total_bill", "tip")

How do I add a title to this Seaborne plot? Let’s give it a title ‘I AM A TITLE’.

tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col="sex", row="smoker", margin_titles=True)
g.map(sns.plt.scatter, "total_bill", "tip")


回答 0

在这些行之后:

plt.subplots_adjust(top=0.9)
g.fig.suptitle('THIS IS A TITLE, YOU BET') # can also get the figure from plt.gcf()

如果添加字幕而不调整轴,则seafacet字幕标题会与之重叠。

(使用不同的数据):

After those lines:

plt.subplots_adjust(top=0.9)
g.fig.suptitle('THIS IS A TITLE, YOU BET') # can also get the figure from plt.gcf()

If you add a suptitle without adjusting the axis, the seaborn facet titles overlap it.

(With different data):


回答 1

在ipython笔记本中,这对我有用!

sns.plt.title('YOUR TITLE HERE')

In ipython notebook, this worked for me!

sns.plt.title('YOUR TITLE HERE')

回答 2

g.fig.subplots_adjust(top=0.9)
g.fig.suptitle('Title', fontsize=16)

此处提供更多信息:http : //matplotlib.org/api/figure_api.html

g.fig.subplots_adjust(top=0.9)
g.fig.suptitle('Title', fontsize=16)

More info here: http://matplotlib.org/api/figure_api.html


回答 3

对我有用的是:

sns.plt.suptitle('YOUR TITLE HERE')

What worked for me was:

sns.plt.suptitle('YOUR TITLE HERE')


回答 4

plt.suptitle("Title") 

要么

plt.title("Title")

这对我有用。

plt.suptitle("Title") 

or

plt.title("Title")

This worked for me.


回答 5

答案正在使用sns.plt.title()sns.plt.suptitle()不再起作用。

相反,您需要使用matplotlib的title()函数:

import matplotlib.pyplot as plt
sns.FacetGrid(<whatever>)
plt.title("A title")

The answers using sns.plt.title() and sns.plt.suptitle() don’t work anymore.

Instead, you need to use matplotlib’s title() function:

import matplotlib.pyplot as plt
sns.FacetGrid(<whatever>)
plt.title("A title")

回答 6

标题不会与子图标题居中对齐。要设置标题的位置,您可以使用 plt.suptitle("Title", x=center)

就我而言,我的子图位于2×1网格中,因此我能够使用它 bbox = g.axes[0,0].get_position()来找到边界框,然后center=0.5*(bbox.x1+bbox.x2)

The title will not be center aligned with the subplot titles. To set the position of the title you can use plt.suptitle("Title", x=center)

In my case, my subplots were in a 2×1 grid, so I was able to use bbox = g.axes[0,0].get_position() to find the bounding box and then center=0.5*(bbox.x1+bbox.x2)


matplotlib / seaborn:热图图的第一行和最后一行被切成两半

问题:matplotlib / seaborn:热图图的第一行和最后一行被切成两半

用seaborn(和matplotlib关联矩阵)绘制热图时,第一行和最后一行被切成两半。当我运行这个在网上找到的最小代码示例时,也会发生这种情况。

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

data = pd.read_csv('https://raw.githubusercontent.com/resbaz/r-novice-gapminder-files/master/data/gapminder-FiveYearData.csv')
plt.figure(figsize=(10,5))
sns.heatmap(data.corr())
plt.show()

y轴上的标签在正确的位置,但是行并不完全在此处。

几天前,它按预期工作。从那时起,我安装了texlive-xetex,因此我再次将其删除,但是并不能解决我的问题。

有什么想法我可能会错过吗?

When plotting heatmaps with seaborn (and correlation matrices with matplotlib) the first and the last row is cut in halve. This happens also when I run this minimal code example which I found online.

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

data = pd.read_csv('https://raw.githubusercontent.com/resbaz/r-novice-gapminder-files/master/data/gapminder-FiveYearData.csv')
plt.figure(figsize=(10,5))
sns.heatmap(data.corr())
plt.show()

The labels at the y axis are on the correct spot, but the rows aren’t completely there.

A few days ago, it work as intended. Since then, I installed texlive-xetex so I removed it again but it didn’t solve my problem.

Any ideas what I could be missing?


回答 0

不幸的是,matplotlib 3.1.1 打破了海洋热图;并通常使用固定刻度的倒轴。
在当前的开发版本中已修复此问题。你可能因此

  • 恢复到matplotlib 3.1.0
  • 使用matplotlib 3.1.2或更高版本
  • 手动设置热图限制(ax.set_ylim(bottom, top) # set the ylim to bottom, top

Unfortunately matplotlib 3.1.1 broke seaborn heatmaps; and in general inverted axes with fixed ticks.
This is fixed in the current development version; you may hence

  • revert to matplotlib 3.1.0
  • use matplotlib 3.1.2 or higher
  • set the heatmap limits manually (ax.set_ylim(bottom, top) # set the ylim to bottom, top)

回答 1

这是3.1.0和3.1.1之间的matplotlib回归中的错误,您可以通过以下方法更正此错误:

import seaborn as sns
df_corr = someDataFrame.corr()
ax = sns.heatmap(df_corr, annot=True) #notation: "annot" not "annote"
bottom, top = ax.get_ylim()
ax.set_ylim(bottom + 0.5, top - 0.5)

Its a bug in the matplotlib regression between 3.1.0 and 3.1.1 You can correct this by:

import seaborn as sns
df_corr = someDataFrame.corr()
ax = sns.heatmap(df_corr, annot=True) #notation: "annot" not "annote"
bottom, top = ax.get_ylim()
ax.set_ylim(bottom + 0.5, top - 0.5)

回答 2

已使用上述方法修复并手动设置了热图限制。

第一

ax = sns.heatmap(...

检查当前轴

ax.get_ylim()
(5.5, 0.5)

固定于

ax.set_ylim(6.0, 0)

Fixed using the above and setting the heatmap limits manually.

First

ax = sns.heatmap(...

checked the current axes with

ax.get_ylim()
(5.5, 0.5)

Fixed with

ax.set_ylim(6.0, 0)

回答 3

我通过在代码中添加以下行来解决了这一问题matplotlib==3.1.1

ax.set_ylim(sorted(ax.get_xlim(), reverse=True))

注意 起作用的唯一原因是因为x轴未更改,因此使用未来的mpl版本需要您自担风险

I solved it by adding this line in my code, with matplotlib==3.1.1:

ax.set_ylim(sorted(ax.get_xlim(), reverse=True))

NB. The only reason this works is because the x-axis isn’t changed, so use at your own risk with future mpl versions


回答 4

matplotlib 3.1.2已发布-可通过conda-forge在Anaconda云中找到,但我无法通过conda install进行安装。手动替代方法可行:从github下载matplotlib 3.1.2并通过pip安装

 % curl https://codeload.github.com/matplotlib/matplotlib/tar.gz/v3.1.2 --output matplotlib-3.1.2.tar.gz
 % pip install matplotlib-3.1.2.tar.gz

matplotlib 3.1.2 is out – It is available in the Anaconda cloud via conda-forge but I was not able to install it via conda install. The manual alternative worked: Download matplotlib 3.1.2 from github and install via pip

 % curl https://codeload.github.com/matplotlib/matplotlib/tar.gz/v3.1.2 --output matplotlib-3.1.2.tar.gz
 % pip install matplotlib-3.1.2.tar.gz

回答 5

重要性提示所建议的那样,它发生在matplotlib版本3.1.1中

以下解决了我的问题

pip install matplotlib==3.1.0

It happens with matplotlib version 3.1.1 as suggested by importanceofbeingernest

Following solved my problem

pip install matplotlib==3.1.0


回答 6

rustyDev关于conda-forge是正确的,但是我不需要从github下载进行手动pip安装。对我来说,在Windows上,它可以直接工作。而且情节都很好。

https://anaconda.org/conda-forge/matplotlib

conda install -c conda-forge matplotlib

可选点,答案不需要:

之后,我尝试了其他步骤,但没有必要:在conda提示符下:conda search matplotlib –info未显示新版本信息,最新信息为3.1.1。因此,我尝试使用pip进行尝试,pip install matplotlib==3.1.2但是pip说“要求已经满足”

然后根据medium.com/@rakshithvasudev/…获取版本,python - import matplotlib - matplotlib.__version__表明3.1.2已成功安装。

顺便说一句,将Spyder更新到v4.0.0后,我直接遇到了此错误。误差在混淆矩阵图中。几个月前已经提到过这一点。stackoverflow.com/questions/57225685/…已经与这个棘手的问题相关联。

rustyDev is right about conda-forge, but I did not need to do a manual pip install from a github download. For me, on Windows, it worked directly. And the plots are all nice again.

https://anaconda.org/conda-forge/matplotlib

conda install -c conda-forge matplotlib

optional points, not needed for the answer:

Afterwards, I tried other steps, but they are not needed: In conda prompt: conda search matplotlib –info showed no new version info, the most recent info was for 3.1.1. Thus I tried pip using pip install matplotlib==3.1.2 But pip says “Requirement already satisfied”

Then getting the version according to medium.com/@rakshithvasudev/… python - import matplotlib - matplotlib.__version__ shows that 3.1.2 was successfully installed

Btw, I had this error directly after updating Spyder to v4.0.0. The error was in a plot of a confusion matrix. This was mentioned already some months ago. stackoverflow.com/questions/57225685/… which is already linked to this seaborn question.


回答 7

康达安装matplotlib = 3.1.0

这对我有用,并将matplotlib从3.1.1降级到3.1.0,并且热图开始正确运行

conda install matplotlib=3.1.0

This worked for me and downgraded matplotlib from 3.1.1 to 3.1.0 and the heatmaps started to behave correctly


回答 8

我用以下代码解决了这个问题:

I solved this problem with the following code:


使用matplotlib面向对象的界面进行seaborn绘图

问题:使用matplotlib面向对象的界面进行seaborn绘图

我非常喜欢matplotlib以OOP风格使用:

f, axarr = plt.subplots(2, sharex=True)
axarr[0].plot(...)
axarr[1].plot(...)

这样可以更轻松地跟踪多个图形和子图。

问题:如何以这种方式使用seaborn?或者,如何将此示例更改为OOP样式?如何分辨seaborn绘图功能(例如lmplot哪个Figure或哪个)Axes

I strongly prefer using matplotlib in OOP style:

f, axarr = plt.subplots(2, sharex=True)
axarr[0].plot(...)
axarr[1].plot(...)

This makes it easier to keep track of multiple figures and subplots.

Question: How to use seaborn this way? Or, how to change this example to OOP style? How to tell seaborn plotting functions like lmplot which Figure or Axes it plots to?


回答 0

这在某种程度上取决于您使用的是哪种功能。

Seaborn中的绘图功能大致分为两类

  • “轴级”功能,包括regplotboxplotkdeplot,和许多其他
  • “图级”功能,包括lmplotfactorplotjointplot和一个或两个其他

通过采用显式ax参数并返回Axes对象来标识第一组。如此建议,您可以将它们传递Axes给它们,从而以“面向对象”的方式使用它们:

f, (ax1, ax2) = plt.subplots(2)
sns.regplot(x, y, ax=ax1)
sns.kdeplot(x, ax=ax2)

轴级功能将仅绘制到,Axes并且不会与图形混淆,因此它们可以在面向对象的matplotlib脚本中完美地愉快地共存。

第二组功能(图级)的特征在于,生成的图可能包含多个轴,这些轴始终以“有意义”的方式组织。这意味着功能需要完全控制图形,因此不可能将图形绘制lmplot到已经存在的图形上。调用该函数始终会初始化图形,并将其设置为要绘制的特定图。

但是,一旦调用lmplot,它将返回类型的对象FacetGrid。该对象具有一些对生成的图进行操作的方法,这些方法对图的结构有所了解。它还在FacetGrid.figFacetGrid.axes参数处公开了基础图形和轴数组。该jointplot功能非常相似,但是它使用一个JointGrid对象。因此,您仍然可以在面向对象的上下文中使用这些函数,但是所有自定义必须在调用该函数之后进行。

It depends a bit on which seaborn function you are using.

The plotting functions in seaborn are broadly divided into two classes

  • “Axes-level” functions, including regplot, boxplot, kdeplot, and many others
  • “Figure-level” functions, including lmplot, factorplot, jointplot and one or two others

The first group is identified by taking an explicit ax argument and returning an Axes object. As this suggests, you can use them in an “object oriented” style by passing your Axes to them:

f, (ax1, ax2) = plt.subplots(2)
sns.regplot(x, y, ax=ax1)
sns.kdeplot(x, ax=ax2)

Axes-level functions will only draw onto an Axes and won’t otherwise mess with the figure, so they can coexist perfectly happily in an object-oriented matplotlib script.

The second group of functions (Figure-level) are distinguished by the fact that the resulting plot can potentially include several Axes which are always organized in a “meaningful” way. That means that the functions need to have total control over the figure, so it isn’t possible to plot, say, an lmplot onto one that already exists. Calling the function always initializes a figure and sets it up for the specific plot it’s drawing.

However, once you’ve called lmplot, it will return an object of the type FacetGrid. This object has some methods for operating on the resulting plot that know a bit about the structure of the plot. It also exposes the underlying figure and array of axes at the FacetGrid.fig and FacetGrid.axes arguments. The jointplot function is very similar, but it uses a JointGrid object. So you can still use these functions in an object-oriented context, but all of your customization has to come after you’ve called the function.


如何更改海图的图形大小?

问题:如何更改海图的图形大小?

如何更改图像尺寸以适合打印?

例如,我想使用A4纸,其横向尺寸为11.7英寸乘8.27英寸。

How do I change the size of my image so it’s suitable for printing?

For example, I’d like to use to A4 paper, whose dimensions are 11.7 inches by 8.27 inches in landscape orientation.


回答 0

您需要提前创建matplotlib图形和轴对象,并指定图形的大小:

from matplotlib import pyplot
import seaborn

import mylib

a4_dims = (11.7, 8.27)
df = mylib.load_data()
fig, ax = pyplot.subplots(figsize=a4_dims)
seaborn.violinplot(ax=ax, data=df, **violin_options)

You need to create the matplotlib Figure and Axes objects ahead of time, specifying how big the figure is:

from matplotlib import pyplot
import seaborn

import mylib

a4_dims = (11.7, 8.27)
df = mylib.load_data()
fig, ax = pyplot.subplots(figsize=a4_dims)
seaborn.violinplot(ax=ax, data=df, **violin_options)

回答 1

您还可以通过rc使用'figure.figsize'seaborn set方法中的key 将字典传递给参数来设置图形大小:

import seaborn as sns

sns.set(rc={'figure.figsize':(11.7,8.27)})

其他替代可以是使用figure.figsizercParams对集合的数字大小如下:

from matplotlib import rcParams

# figure size in inches
rcParams['figure.figsize'] = 11.7,8.27

可以在matplotlib文档中找到更多详细信息

You can also set figure size by passing dictionary to rc parameter with key 'figure.figsize' in seaborn set method:

import seaborn as sns

sns.set(rc={'figure.figsize':(11.7,8.27)})

Other alternative may be to use figure.figsize of rcParams to set figure size as below:

from matplotlib import rcParams

# figure size in inches
rcParams['figure.figsize'] = 11.7,8.27

More details can be found in matplotlib documentation


回答 2

您可以将上下文设置为poster或手动设置fig_size

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

np.random.seed(0)
n, p = 40, 8
d = np.random.normal(0, 2, (n, p))
d += np.log(np.arange(1, p + 1)) * -5 + 10


# plot
sns.set_style('ticks')
fig, ax = plt.subplots()
# the size of A4 paper
fig.set_size_inches(11.7, 8.27)
sns.violinplot(data=d, inner="points", ax=ax)    
sns.despine()

fig.savefig('example.png')

You can set the context to be poster or manually set fig_size.

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

np.random.seed(0)
n, p = 40, 8
d = np.random.normal(0, 2, (n, p))
d += np.log(np.arange(1, p + 1)) * -5 + 10


# plot
sns.set_style('ticks')
fig, ax = plt.subplots()
# the size of A4 paper
fig.set_size_inches(11.7, 8.27)
sns.violinplot(data=d, inner="points", ax=ax)    
sns.despine()

fig.savefig('example.png')


回答 3

请注意,如果你正在试图通过一个“数字级别”的方法在seaborn(例如lmplotcatplot/ factorplotjointplot),你可以而且应该在参数中指定使用这个heightaspect

sns.catplot(data=df, x='xvar', y='yvar', 
    hue='hue_bar', height=8.27, aspect=11.7/8.27)

请参阅https://github.com/mwaskom/seaborn/issues/488使用matplotlib面向对象的界面使用seaborn进行绘图,以了解有关图形级方法不遵守轴规格的事实的更多详细信息。

Note that if you are trying to pass to a “figure level” method in seaborn (for example lmplot, catplot / factorplot, jointplot) you can and should specify this within the arguments using height and aspect.

sns.catplot(data=df, x='xvar', y='yvar', 
    hue='hue_bar', height=8.27, aspect=11.7/8.27)

See https://github.com/mwaskom/seaborn/issues/488 and Plotting with seaborn using the matplotlib object-oriented interface for more details on the fact that figure level methods do not obey axes specifications.


回答 4

首先导入matplotlib并使用它来设置图形的大小

from matplotlib import pyplot as plt
import seaborn as sns

plt.figure(figsize=(15,8))
ax = sns.barplot(x="Word", y="Frequency", data=boxdata)

first import matplotlib and use it to set the size of the figure

from matplotlib import pyplot as plt
import seaborn as sns

plt.figure(figsize=(15,8))
ax = sns.barplot(x="Word", y="Frequency", data=boxdata)

回答 5

这也将起作用。

from matplotlib import pyplot as plt
import seaborn as sns    

plt.figure(figsize=(15,16))
sns.countplot(data=yourdata, ...)

This shall also work.

from matplotlib import pyplot as plt
import seaborn as sns    

plt.figure(figsize=(15,16))
sns.countplot(data=yourdata, ...)

回答 6

可以使用以下方法完成:

plt.figure(figsize=(15,8))
sns.kdeplot(data,shade=True)

This can be done using:

plt.figure(figsize=(15,8))
sns.kdeplot(data,shade=True)

回答 7

对于我的情节(sns因子图),建议的答案不起作用。

因此我用

plt.gcf().set_size_inches(11.7, 8.27)

紧随seaborn的情节之后(因此无需将斧头传递给seaborn或更改rc设置)。

For my plot (a sns factorplot) the proposed answer didn’t works fine.

Thus I use

plt.gcf().set_size_inches(11.7, 8.27)

Just after the plot with seaborn (so no need to pass an ax to seaborn or to change the rc settings).


回答 8

除了关于返回多图网格对象的“图形级别”方法的elz答案之外,还可以使用以下方法显式设置图形的高度和宽度(即不使用宽高比):

import seaborn as sns 

g = sns.catplot(data=df, x='xvar', y='yvar', hue='hue_bar')
g.fig.set_figwidth(8.27)
g.fig.set_figheight(11.7)

In addition to elz answer regarding “figure level” methods that return multi-plot grid objects it is possible to set the figure height and width explicitly (that is without using aspect ratio) using the following approach:

import seaborn as sns 

g = sns.catplot(data=df, x='xvar', y='yvar', hue='hue_bar')
g.fig.set_figwidth(8.27)
g.fig.set_figheight(11.7)

回答 9

保罗·H(Paul H)和李·李(J. Li)给出的头等答案并非适用于所有类型的海洋人物。对于FacetGrid类型(例如sns.lmplot()),请使用sizeaspect参数。

Size 更改高度和宽度,并保持宽高比。

Aspect 只改变宽度,保持高度不变。

始终可以通过使用这两个参数来获得所需的大小。

信用:https : //stackoverflow.com/a/28765059/3901029

The top answers by Paul H and J. Li do not work for all types of seaborn figures. For the FacetGrid type (for instance sns.lmplot()), use the size and aspect parameter.

Size changes both the height and width, maintaining the aspect ratio.

Aspect only changes the width, keeping the height constant.

You can always get your desired size by playing with these two parameters.

Credit: https://stackoverflow.com/a/28765059/3901029


Seaborn地块未显示

问题:Seaborn地块未显示

我确定我忘记了一些非常简单的内容,但是我无法获得某些与Seaborn合作的计划。

如果我做:

import seaborn as sns

然后,我照常使用matplotlib创建的任何图都将获得Seaborn样式(背景为灰色网格)。

但是,如果我尝试执行以下示例之一,例如:

In [1]: import seaborn as sns

In [2]: sns.set()

In [3]: df = sns.load_dataset('iris')

In [4]: sns.pairplot(df, hue='species', size=2.5)
Out[4]: <seaborn.axisgrid.PairGrid at 0x3e59150>

pairplot函数返回一个PairGrid对象,但该图未显示。

我有些困惑,因为matplotlib似乎可以正常运行,并且Seaborn样式已应用于其他matplotlib图,但是Seaborn函数似乎没有任何作用。有人知道可能是什么问题吗?

I’m sure I’m forgetting something very simple, but I cannot get certain plots to work with Seaborn.

If I do:

import seaborn as sns

Then any plots that I create as usual with matplotlib get the Seaborn styling (with the grey grid in the background).

However, if I try to do one of the examples, such as:

In [1]: import seaborn as sns

In [2]: sns.set()

In [3]: df = sns.load_dataset('iris')

In [4]: sns.pairplot(df, hue='species', size=2.5)
Out[4]: <seaborn.axisgrid.PairGrid at 0x3e59150>

The pairplot function returns a PairGrid object, but the plot doesn’t show up.

I’m a little confused because matplotlib seems to be functioning properly, and the Seaborn styles are applied to other matplotlib plots, but the Seaborn functions don’t seem to do anything. Does anybody have any idea what might be the problem?


回答 0

使用seaborn创建的图需要像普通的matplotlib图一样显示。可以使用

plt.show()

来自matplotlib的功能。

最初,我发布了使用seaborn(sns.plt.show())中已导入的matplotlib对象的解决方案,但是这被认为是不好的做法。因此,只需直接导入matplotlib.pyplot模块并使用

import matplotlib.pyplot as plt
plt.show()

如果使用IPython笔记本,则可以调用内联后端以消除在每次绘制后调用show的必要性。各自的魔力是

%matplotlib inline

Plots created using seaborn need to be displayed like ordinary matplotlib plots. This can be done using the

plt.show()

function from matplotlib.

Originally I posted the solution to use the already imported matplotlib object from seaborn (sns.plt.show()) however this is considered to be a bad practice. Therefore, simply directly import the matplotlib.pyplot module and show your plots with

import matplotlib.pyplot as plt
plt.show()

If the IPython notebook is used the inline backend can be invoked to remove the necessity of calling show after each plot. The respective magic is

%matplotlib inline

回答 1

我经常问这个问题,而且总是花些时间才能找到要搜索的内容:

import seaborn as sns
import matplotlib.pyplot as plt

plt.show()  # <--- This is what you are looking for

请注意:在Python 2中,您也可以使用sns.plt.show(),但在Python 3中则不能。

完整的例子

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Visualize C_0.99 for all languages except the 10 with most characters."""

import seaborn as sns
import matplotlib.pyplot as plt

l = [41, 44, 46, 46, 47, 47, 48, 48, 49, 51, 52, 53, 53, 53, 53, 55, 55, 55,
     55, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 57, 57, 58, 58, 58,
     58, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 60, 60, 60, 60, 60, 60, 61,
     61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 62, 62, 62, 62, 62, 62, 62, 62,
     62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 64, 64, 64, 64, 64, 64, 64, 65,
     65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 66, 66, 66, 66, 66, 66, 66,
     67, 67, 67, 67, 67, 67, 67, 67, 68, 68, 68, 68, 68, 69, 69, 69, 70, 70,
     70, 70, 71, 71, 71, 71, 71, 72, 72, 72, 72, 73, 73, 73, 73, 73, 73, 73,
     74, 74, 74, 74, 74, 75, 75, 75, 76, 77, 77, 78, 78, 79, 79, 79, 79, 80,
     80, 80, 80, 81, 81, 81, 81, 83, 84, 84, 85, 86, 86, 86, 86, 87, 87, 87,
     87, 87, 88, 90, 90, 90, 90, 90, 90, 91, 91, 91, 91, 91, 91, 91, 91, 92,
     92, 93, 93, 93, 94, 95, 95, 96, 98, 98, 99, 100, 102, 104, 105, 107, 108,
     109, 110, 110, 113, 113, 115, 116, 118, 119, 121]

sns.distplot(l, kde=True, rug=False)

plt.show()

I come to this question quite regularly and it always takes me a while to find what I search:

import seaborn as sns
import matplotlib.pyplot as plt

plt.show()  # <--- This is what you are looking for

Please note: In Python 2, you can also use sns.plt.show(), but not in Python 3.

Complete Example

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Visualize C_0.99 for all languages except the 10 with most characters."""

import seaborn as sns
import matplotlib.pyplot as plt

l = [41, 44, 46, 46, 47, 47, 48, 48, 49, 51, 52, 53, 53, 53, 53, 55, 55, 55,
     55, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 57, 57, 58, 58, 58,
     58, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 60, 60, 60, 60, 60, 60, 61,
     61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 62, 62, 62, 62, 62, 62, 62, 62,
     62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 64, 64, 64, 64, 64, 64, 64, 65,
     65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 66, 66, 66, 66, 66, 66, 66,
     67, 67, 67, 67, 67, 67, 67, 67, 68, 68, 68, 68, 68, 69, 69, 69, 70, 70,
     70, 70, 71, 71, 71, 71, 71, 72, 72, 72, 72, 73, 73, 73, 73, 73, 73, 73,
     74, 74, 74, 74, 74, 75, 75, 75, 76, 77, 77, 78, 78, 79, 79, 79, 79, 80,
     80, 80, 80, 81, 81, 81, 81, 83, 84, 84, 85, 86, 86, 86, 86, 87, 87, 87,
     87, 87, 88, 90, 90, 90, 90, 90, 90, 91, 91, 91, 91, 91, 91, 91, 91, 92,
     92, 93, 93, 93, 94, 95, 95, 96, 98, 98, 99, 100, 102, 104, 105, 107, 108,
     109, 110, 110, 113, 113, 115, 116, 118, 119, 121]

sns.distplot(l, kde=True, rug=False)

plt.show()

Gives


回答 2

为了避免混淆(评论中似乎有一些)。假设您使用Jupyter:

%matplotlib inline>显示的曲线INSIDE笔记本

sns.plt.show()> 在笔记本的外侧显示图

%matplotlib inline从某种意义上讲,即使绘图被调用,绘图也会显示笔记本中,它将覆盖sns.plt.show()sns.plt.show()

是的,很容易将行包含到您的配置中:

在IPython Notebook中内联自动运行%matplotlib

但是在实际代码中将其与导入保持在一起似乎是一个更好的约定。

To avoid confusion (as there seems to be some in the comments). Assuming you are on Jupyter:

%matplotlib inline > displays the plots INSIDE the notebook

sns.plt.show() > displays the plots OUTSIDE of the notebook

%matplotlib inline will OVERRIDE sns.plt.show() in the sense that plots will be shown IN the notebook even when sns.plt.show() is called.

And yes, it is easy to include the line in to your config:

Automatically run %matplotlib inline in IPython Notebook

But it seems a better convention to keep it together with imports in the actual code.


回答 3

这对我有用

import matplotlib.pyplot as plt
import seaborn as sns
.
.
.
plt.show(sns)

This worked for me

import matplotlib.pyplot as plt
import seaborn as sns
.
.
.
plt.show(sns)

回答 4

我的建议是给

plt.figure()并给出一些sns图。例如

sns.distplot(data)

尽管看起来它不会显示任何图,但是当您最大化图形时,您将能够看到该图。

My advice is just to give a

plt.figure() and give some sns plot. For example

sns.distplot(data).

Though it will look it doesnt show any plot, When you maximise the figure, you will be able to see the plot.


回答 5

如果您在IPython控制台(不能使用%matplotlib inline)而不是Jupyter笔记本中进行绘制,并且不想plt.show()重复运行,则可以使用以下命令启动IPython控制台ipython --pylab

$ ipython --pylab     
Python 3.6.6 |Anaconda custom (64-bit)| (default, Jun 28 2018, 17:14:51) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.0.1 -- An enhanced Interactive Python. Type '?' for help.
Using matplotlib backend: Qt5Agg

In [1]: import seaborn as sns

In [2]: tips = sns.load_dataset("tips")

In [3]: sns.relplot(x="total_bill", y="tip", data=tips) # you can see the plot now

If you plot in IPython console (where you can’t use %matplotlib inline) instead of Jupyter notebook, and don’t want to run plt.show() repeatedly, you can start IPython console with ipython --pylab:

$ ipython --pylab     
Python 3.6.6 |Anaconda custom (64-bit)| (default, Jun 28 2018, 17:14:51) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.0.1 -- An enhanced Interactive Python. Type '?' for help.
Using matplotlib backend: Qt5Agg

In [1]: import seaborn as sns

In [2]: tips = sns.load_dataset("tips")

In [3]: sns.relplot(x="total_bill", y="tip", data=tips) # you can see the plot now

回答 6

从您的代码片段的风格可以看出,我想您使用的是IPython而不是Jupyter Notebook。

在GitHub上的此期中,IPython的一名成员在2016年明确指出,图表的显示仅在“仅在Jupyter内核中有效”时才起作用。因此, %matplotlib inline将无法正常工作。

我只是遇到了同样的问题,建议您使用Jupyter Notebook进行可视化。

To tell from the style of your code snippet, I suppose you were using IPython rather than Jupyter Notebook.

In this issue on GitHub, it was made clear by a member of IPython in 2016 that the display of charts would only work when “only work when it’s a Jupyter kernel”. Thus, the %matplotlib inline would not work.

I was just having the same issue and suggest you use Jupyter Notebook for the visualization.


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