Pandas plot doesn't show

前端 未结 4 810

When using this in a script (not IPython), nothing happens, i.e. the plot window doesn\'t appear :

import numpy as np
import pandas as pd
ts = pd.Series(np.r         


        
4条回答
  •  被撕碎了的回忆
    2020-12-04 21:12

    Once you have made your plot, you need to tell matplotlib to show it. The usual way to do things is to import matplotlib.pyplot and call show from there:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
    ts.plot()
    plt.show()
    

    Since you have requested not to do that (why?), you could use the following [NOTE: This no longer appears to work with newer versions of pandas]:

    import numpy as np
    import pandas as pd
    ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
    ts.plot()
    pd.tseries.plotting.pylab.show()
    

    But all you are doing there is finding somewhere that matplotlib has been imported in pandas, and calling the same show function from there.

    Are you trying to avoid calling matplotlib in an effort to speed things up? If so then you are really not speeding anything up, since pandas already imports pyplot:

    python -mtimeit -s 'import pandas as pd'
    100000000 loops, best of 3: 0.0122 usec per loop
    
    python -mtimeit -s 'import pandas as pd; import matplotlib.pyplot as plt'
    100000000 loops, best of 3: 0.0125 usec per loop
    

    Finally, the reason the example you linked in comments doesn't need the call to matplotlib is because it is being run interactively in an iPython notebook, not in a script.

提交回复
热议问题