简体   繁体   English

用辅助y轴绘制大熊猫列并将图表保存到单个pdf

[英]Plot pandas columns with secondary y -axis and saving charts to a single pdf

I am trying to create multiple time-series plots using data in a Pandas DataFrame columns. 我正在尝试使用Pandas DataFrame列中的数据创建多个时间序列图。 I want to save all these charts to a single pdf file. 我想将所有这些图表保存到单个pdf文件中。 The challenge is that these charts all have a secondary y-axis which has a different scale (see Col Z below). 面临的挑战是这些图表都具有一个次级y轴,其比例不同(请参见下面的Z栏)。 I have seen examples of saving multiple charts to pdf, and examples of plotting a singe chart with a secondary y-axis, but don't know how to combine the two. 我已经看到了将多个图表保存为pdf的示例,以及使用次要y轴绘制单幅图表的示例,但不知道如何将两者结合起来。 My actual DataFrame has 50 columns, so doing it manually would be tedious. 我的实际DataFrame有50列,因此手动进行比较麻烦。 Thanks in advance. 提前致谢。

Here is what I tried: 这是我尝试过的:

df1 = pd.DataFrame(np.random.rand(10, 4))
df1.columns = ['A', 'B', 'C', 'Z']
date_range = pd.date_range('1/31/2011', periods=10, freq='M')
df1['Z'] = 100*df1['Z']
df1.plot(kind='line', subplots=True, secondary_y=['Z'])
#

import matplotlib.backends.backend_pdf
pdf = matplotlib.backends.backend_pdf.PdfPages("output.pdf")
plt.figure()
for cols in df1.columns:
    df1.plot(y=cols, secondary_y=['Z'])
    pdf.savefig(fig)
pdf.close()

As I understand, I think this is what you are trying. 据我了解,我认为这就是您正在尝试的方法。 This generate 4 graphs with 2 series in each one. 这将生成4个图形,每个图形有2个系列。 Series A , B , C are plotted together with serie Z : 系列ABCZ系列一起绘制:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.backends.backend_pdf

df1 = pd.DataFrame(np.random.rand(10, 4))
df1.columns = ['A', 'B', 'C', 'Z']
date_range = pd.date_range('1/31/2011', periods=10, freq='M')
df1['Z'] = 100*df1['Z']
df1.plot(kind='line', subplots=True, secondary_y=['Z'])

with matplotlib.backends.backend_pdf.PdfPages("output.pdf") as pdf:
    for cols in df1.columns:
        ## plot 1
        fig, ax1 = plt.subplots()
        df1.plot(y=cols, ax=ax1, color='C1')
        ax1.legend(loc=2)
        ## plot 2
        ax2 = ax1.twinx()
        df1.plot(y='Z', ax=ax2)
        pdf.savefig()

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

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