Pandas循环遍历groupby并绘制每个组

时间:2017-11-29 23:36:28

标签: pandas matplotlib plot group-by

我正在尝试遍历groupby对象并绘制每个组。但我遇到了一些问题。有人可以告诉我哪里出错了吗?

class processCSV extends Command
{   
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'process:csv';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Get and process the CSV file uploaded by admin and update the database.';
    private $repo;
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(EntityManagerInterface $repo)
    {
        $this->repo = $repo;
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
       ... something

            $repository = $this->repo->getRepository(Site::class);
            $site = $repository->findOneBy(
                array(
                    'bpId' =>$code 
                ) ); 
    }
}

似乎我很接近,但只是在某些地方存在一些问题。

  1. 第一个问题是groupby对象中有5个组。我得到了我想要的5个数字,但只有第一个有图(线)。其他数字是空白的,上面有正确的标题,任何想法我的代码有什么问题?
  2. 如何将组列/键设置为x轴,我尝试过这个x = group.desiredx但它没有做任何事情。
  3. 的myKey |一年| VAL1 | VAL2
    物品1 | 2000 | 5 | 34个
    ITEM2 | 2001 | 45 | 34个
    项目3 | 2002 | 34 | 34个
    物品1 | 2000 | 22 | 65个
    ITEM2 | 2001 | 34 | 54个
    项目3 | 2002 | 12 | 54个
    物品1 | 2000 | 23 | 54个
    ITEM2 | 2001 | 34 | 34个
    项目3 | 2002 | 21 | 21个

2 个答案:

答案 0 :(得分:2)

在y轴上绘制的值为Interface i=()->System.out.println("1");System.out.println("2");System.out.println("3");System.out.println("4"); i.print(); Interface i=()->System.out.println("1"); System.out.println("2"); System.out.println("3"); System.out.println("4"); i.print(); 。您将1设置为大于2ylim的值。因此,您看不到5ylim=[5,20]的值。

1设置为一些合理的数字,例如2将允许您查看数据。

此外,ylim会根据其索引绘制数据,因为ylim=[0,3]中没有group.val1.plot。而是将"year"作为group.val1值。

"val1"

答案 1 :(得分:0)

感谢ImportanceOfBeingErnest,我得到了我想要的结果。以下是代码的完整调整版本,适用于将来可能需要它的任何人。我添加了legend = False,没有这个val1和val2写在彼此之上,看起来很乱。

import pandas as pd
import matplotlib.pyplot as plt

 df = pd.DataFrame([['item1',2000,1, 2], ['item1',2001,1, 2], ['item1',2002,1, 2], 
          ['item2',2000,1, 2], ['item2',2001,3, 2], ['item2',2002,1, 2]],
          columns=['mykey', 'year','val1','val2'])

 grouped = df.groupby('mykey')
 for name,group in grouped:
  fig = plt.figure()
   ax1 = fig.add_subplot(111)
  group.plot.line(ax=ax1, ylim=[0,3], color='red',x="year",y="val1", legend 
  = False, xticks = [2000,2001,2002])
  ax1.set_ylabel('val1  ssssssss')
  ax2 = ax1.twinx()
  group.plot.line(ax=ax2, ylim=[0,3], color='blue',x="year",y="val2", legend 
  = False, xticks = [2000,2001,2002])
  ax2.set_ylabel('val2 dddddd')
  plt.title(str(name), fontsize=15)

   plt.show()
相关问题