【问题标题】:Plotting Multiple Items as line graph in Matplotlib在 Matplotlib 中将多个项目绘制为折线图
【发布时间】:2015-10-01 11:24:11
【问题描述】:

我有一个像这样的熊猫数据框:

Date     Allotment  NDII_Mean  NDVI_Mean  RGR_Mean  SATVI_Mean            
1984137   Arnston  -0.053650   0.414868  0.938309    0.332712   
1984185   Arnston   0.074928   0.558329  0.867951    0.334555   
1984249   Arnston  -0.124691   0.352225  1.041513    0.331821   
1985139   Arnston  -0.075537   0.468092  0.929414    0.383750   
1985171   Arnston   0.017400   0.493443  0.889835    0.314717   
1986206   Annex     0.151539   0.626690  0.775202    0.332507   
1986238   Annex     0.142235   0.604764  0.823083    0.303600   
1987241   Annex    -0.005423   0.506760  0.911124    0.338675   
1987257   Annex    -0.058166   0.449052  0.961348    0.336879

我想根据分配进行绘图,所以我需要使用 groupby。因此,对于每个分配,我想要 X 轴上的日期,以及名称中具有平均值的所有四列,在图表上显示为线条,它们在 Y 轴上的值。然后我会将它们保存为 pdf,尽管如果有人知道另一种方式,我没有必要这样做。我可以使用此代码绘制一个值(在此示例中我将使用 NDII_Mean),但我想绘制所有四列而不仅仅是一列。我使用的代码是:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

df=pd.read_csv('C:/Users/Stefano/Documents/Hurst_plots.csv')

with PdfPages('C:/Users/Stefano/Documents/Hurst_plots.pdf') as pdf:
   for i, group in df.groupby('Allotment'):

        plt.ylabel('Values')
        plt.figure()

        Hurst_plots=group.plot(x='Date', y='NDII_Mean',title=str(i)).get_figure()
        pdf.savefig(Hurst_plots) 

这是其中一个图的样子(与显示的数据不同,因为我缩短了示例表):

编辑:

这通过添加编辑这一行来工作

Hurst_plots=group.plot(x='Date', y=['NDII_Mean', 'RGR_Mean', 'SATVI_Mean', 'SWIR32_Mean'],title=str(i)).get_figure()

但有人知道如何将图例完全移出图表吗?

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    我在使用 pandas 制作图形方面有过不同的经验,大多数时候我最终将列从数据框中拉出为 numpy 数组,并使用它直接使用 matplotlib 进行绘图。就个人而言,我觉得我可以更好地控制使用 matplotlib 本身的绘图,例如样式绘图、线条颜色(我经常发现自己根据一些计算动态生成 RGB 三元组)和控制图例!我首先建议通过 matplotlib 文档搜索,尝试在 matplotlib 中搜索多线图。看起来您正在尝试绘制时间序列。 Matplotlib 有很好的(虽然一开始有点混乱)界面来处理日期,所以一旦你弄清楚事情是如何工作的,你就可以根据自己的喜好进行自定义。

    这是我最近用来生成多线时间序列图的 sn-p,请注意使用这个最近添加的样式功能,它使图看起来非常漂亮。取自 ipython 笔记本。

    import pandas as pd
    from matplotlib import pyplot as plt
    from matplotlib import dates as mdates
    %matplotlib inline
    import datetime
    from datetime import datetime as dt
    
    plt.style.use('fivethirtyeight')
    
    months = mdates.MonthLocator(range(1,13), bymonthday=1)
    monthsFmt = mdates.DateFormatter('%b')
    
    fig, ax = plt.subplots()
    plt.hold(True)
    for year in range(2010,2016):
        vals = dfs[str(year)]['my_awesome_points'].cumsum().values
        adjusted_d_obj = ['2014'+x[4:] for x in dfs[str(year)]['date']]
        date_objs = [dt.strptime(x, '%Y-%m-%d') for x in adjusted_d_obj]
        dates = [mdates.date2num(x) for x in date_objs]
        #dateints = range(len(dates))
        if year == 2015:    
            ax.plot_date(dates, vals, '-', color=colors[str(year)],                          label=str(year))
        else:
            ax.plot_date(dates,vals, 'r-', color=colors[str(year)],    label=str(year), alpha=0.4)
    fig.set_size_inches((14,10))
    fig.set_dpi(800)
    
    ax.grid(True)
    fig.autofmt_xdate()
    ax.xaxis.set_major_locator(months)
    ax.xaxis.set_major_formatter(monthsFmt)
    
    plt.savefig('sick_pick.png')
    

    它使图表看起来像

    就我而言,我有一个预先存在的数据框字典,其中每个字典都按年份作为键访问。可以保存为 PDF,保存为 PNG 图像文件更容易我认为如上所示 plt.savefig('filename.png') 应该可以工作。 PDF 功能绝对很棒。我有唠叨的客户(不知道他们在说什么)要求报告/图表等。您可以设置一个循环并编写一个包含成百上千页的 PDF,其中每一页都是带有标题的格式精美的图表,图例,轴标签等。传统上,对 matplotlib 的抱怨是干燥和通用的图表。新的 matplotlib 样式非常好看!

    编辑: 检查这个很棒的答案来解决你的传说问题。 https://stackoverflow.com/a/4701285/2639868

    【讨论】:

      猜你喜欢
      • 2021-11-01
      • 2017-01-02
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-27
      相关资源
      最近更新 更多