【问题标题】:Plotting scatter figures in for loop, generating just one figure: Python在 for 循环中绘制散点图,只生成一个图:Python
【发布时间】:2016-05-21 21:08:58
【问题描述】:

我只想生成一个图形,其中包含我在 for 循环中生成的所有散点图,当然,在循环内的每次迭代之间更改颜色。到目前为止,这是我的代码。它确实单独绘制每个散点图,但我想同时显示所有曲线。任何帮助表示赞赏!

import sys
import getopt
import os 
import numpy as np
import pandas as pd
import datetime
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.pyplot import cm 



def usage():
  print "\nThis is the usage function\n"
  print 'Usage:\n'
  print 'YEAR: plotData -y [option]'
  print 'HELP: plotData -h'

def main(argv):
  try:
      opts, args = getopt.getopt(sys.argv[1:], ':y:h', ['year=', 'help'])
      if not opts:
        print 'No options supplied'
        usage()
  except getopt.GetoptError,e:
       print e
       usage()
       sys.exit(2)

  for opt, arg in opts:
     if opt in ('-h', '--help'):
         usage()
         sys.exit(2)

     elif opt in ('-y', '--year'):
         year_data = arg
         print 'YEAR: '+ year_data + ' Stations:\n'

         for dirname, dirnames, filenames in os.walk(year_data) :

             for sta in filenames:
                 N = len(filenames)
                 SplitName = sta.split('.', 3)
                 StaName =  SplitName[0]
                 M = filenames.index(sta)
                 comp = SplitName[2]
                 print StaName

                 f = os.path.join(dirname, sta)
                 YYYYJJJ = np.loadtxt(f, dtype='float', unpack=True)
                 xdates = [datetime.datetime.strptime(str(int(date)),'%Y%j') for date in YYYYJJJ]
                 cons = len(YYYYJJJ)
                 uno = np.ones((cons), dtype=np.int)
                 uno = uno*M

                 fig1, ax1 = plt.subplots(figsize=(15,10))       
                 #ax1.set_title("Station: "+StaName+','+' Component: '+comp)
                 ax1.set_xlabel('Time')
                 ax1.set_ylim(-1, N+2)
                 ax1.axes.get_yaxis().set_visible(False)
                 ax1.grid(True)

                 ax1.scatter(xdates,uno, c='b', alpha=1, marker=(5, 0), s=30)
                 plt.hold(True)
                 plt.show()
                 #fig1.savefig('example'+'.pdf', format='pdf', dpi=1000) 

     else:
         print "Input parameters are not recognized, aborting"
         sys.exit(2)

if __name__ =='__main__':
    main(sys.argv[1:]) 

正在读取的表的示例是下一个(在名为“2016”的目录中):

file: CAO2.2016.HHZ.dat

2016001
2016002
2016003
2016004
2016005
2016006
2016007
2016008
2016009
2016010
2016011
2016012
2016013
2016014
2016015
2016016
2016017
2016018
2016019
2016020
2016021
2016022
2016023
2016024
2016025
2016026
2016027

【问题讨论】:

    标签: python for-loop numpy matplotlib


    【解决方案1】:

    通过取消缩进将图形定义和plt.show()移到循环之外,如下所示:

    fig1, ax1 = plt.subplots(figsize=(15,10))
    #ax1.set_title("Station: "+StaName+','+' Component: '+comp)
    ax1.set_xlabel('Time')
    ax1.set_ylim(-1, N+2)
    ax1.axes.get_yaxis().set_visible(False)
    ax1.grid(True) 
    
    for sta in filenames:
        N = len(filenames)
        SplitName = sta.split('.', 3)
        StaName =  SplitName[0]
        M = filenames.index(sta)
        comp = SplitName[2]
        print StaName
    
        f = os.path.join(dirname, sta)
        YYYYJJJ = np.loadtxt(f, dtype='float', unpack=True)
        xdates = [datetime.datetime.strptime(str(int(date)),'%Y%j')
                  for date in YYYYJJJ]
        cons = len(YYYYJJJ)
        uno = np.ones((cons), dtype=np.int)
        uno = uno*M
        ax1.scatter(xdates,uno, c='b', alpha=1, marker=(5, 0), s=30)
    
    plt.show()
    

    【讨论】:

    • 你也可以顺便把N = len(filenames)去掉
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 2021-02-20
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多