简体   繁体   English

多个matplotlib绘图在同一图中+到pdf-Python

[英]Multiple matplotlib plots in same figure + in to pdf-Python

I'm plotting some data based on pandas dataframes and series. 我正在根据pandas数据帧和系列绘制一些数据。 Following is a part of my code. 以下是我的代码的一部分。 This code gives an error. 此代码出错。

RuntimeError: underlying C/C++ object has been deleted


from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
fig = plt.figure()

dfs = df['col2'].resample('10t', how='count')
dfs.plot()
plt.show()

reg = df.groupby('col1').size()
reg.sort()
reg[-10:].plot(kind='barh')
plt.show()

pp = PdfPages('foo.pdf')
fig.savefig(pp, format='pdf') 
pp.close()

I have two questions. 我有两个问题。

  1. How to plot multiple plots in one output?(Here I get multiple outputs for each and every plot) 如何在一个输出中绘制多个图?(这里我为每个图获得多个输出)
  2. How to write all these plots in to one pdf? 如何将所有这些图写入一个pdf?

I found this as a related question. 我发现是一个相关的问题。

Following is the part of code which gave me the expected result, there may be more elegant ways to do this; 以下是给我预期结果的代码部分,可能有更优雅的方法来做到这一点;

def plotGraph(X):
    fig = plt.figure()
    X.plot()
    return fig


plot1 = plotGraph(dfs)
plot2 = plotGraph2(reg[:-10])
pp = PdfPages('foo.pdf')
pp.savefig(plot1)
pp.savefig(plot2)
pp.close()

Please see the following for targeting different subplots with Pandas. 有关使用Pandas定位不同子图的信息,请参阅以下内容

I am assuming you need 2 subplots (in row fashion). 我假设您需要2个子图(以行方式)。 Thus, your code may be modified as follows: 因此,您的代码可能会被修改如下:

from matplotlib import pyplot as plt

fig, axes = plt.subplots(nrows=2)

dfs = df['col2'].resample('10t', how='count')
dfs.plot(ax=axes[0])

reg = df.groupby('col1').size()
reg.sort()
reg[-10:].plot(kind='barh',ax=axes[0])

plt.savefig('foo.pdf')

matplotlib merges the plots to one figure by default. matplotlib默认情况下将图表合并为一个图形。 See the following snippet - 请参阅以下代码段 -

>>> import pylab as plt
>>> randomList = [randint(0, 40) for _ in range(10)]
>>> randomListTwo = [randint(0, 40) for _ in range(10)]
>>> testFigure = plt.figure(1)
>>> plt.plot(randomList)
[<matplotlib.lines.Line2D object at 0x03F24A90>]
>>> plt.plot(randomListTwo)
[<matplotlib.lines.Line2D object at 0x030B9FB0>]
>>> plt.show()

Gives you a figure like the following - 给你一个如下的数字 -

在此输入图像描述

Also, the file can be easily saved in PDF through the commands you posted - 此外,该文件可以通过您发布的命令轻松保存为PDF格式 -

>>> from matplotlib.backends.backend_pdf import PdfPages
>>> pp = PdfPages('foo.pdf')
>>> testFigure.savefig(pp, format='pdf')
>>> pp.close()

This gave me a PDF with a similar figure. 这给了我一个类似数字的PDF。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM