Unable to “import matplotlib.pyplot as plt” in virtualenv

前端 未结 7 1492
粉色の甜心
粉色の甜心 2020-12-04 07:39

I am working with flask in a virtual environment. I was able to install matplotlib with pip, and I can import matplotlib in a Python session. However, when I im

7条回答
  •  青春惊慌失措
    2020-12-04 07:58

    If you do not want to set a .matplotib/matplotlibrc configuration file, you can circumvent this issue by setting the 'Agg' backend at runtime right after importing matplotlib and before importing matplotlib.pyplot:

    In [1]: import matplotlib
    
    In [2]: matplotlib.use('Agg')
    
    In [3]: import matplotlib.pyplot as plt
    
    In [4]: fig, ax = plt.subplots(1, 1)
    
    In [5]: import numpy as np
    
    In [6]: x = np.linspace(-1., 1.)
    
    In [7]: y = np.sin(x)
    
    In [8]: ax.plot(x, y)
    Out[8]: []
    
    In [9=]: fig.savefig('myplot.png')
    

提交回复
热议问题