【问题标题】:How to create specific plots using Pandas and then store them as PNG files?如何使用 Pandas 创建特定的图,然后将它们存储为 PNG 文件?
【发布时间】:2021-02-09 00:36:24
【问题描述】:

所以我尝试为数据集中的每个特定变量创建直方图,然后将其保存为 PNG 文件。

我的代码如下:

import pandas as pd
import matplotlib.pyplot as plt 
x=combined_databook.groupby('x_1').hist()
x.figure.savefig("x.png")

我不断收到“AttributeError: 'Series' object has no attribute 'figure'”

【问题讨论】:

    标签: python pandas matplotlib plot histogram


    【解决方案1】:

    我不会使用*.hist(),而是使用matplotlib.pyplot.hist()

    例子:

    import matplotlib
    import matplotlib.pyplot as plt
    import numpy as np
    
    y =[10, 20,30,40,100,200,300,400,1000,2000]
    x = np.arange(10)
    fig = plt.figure()
    ax = plt.subplot(111)
    ax.plot(x, y, label='$y = Values')
    plt.title('my plot')
    ax.legend()
    plt.show()
    
    fig.savefig('tada.png')
    
    

    【讨论】:

      【解决方案2】:

      使用matplotlib 创建图形和轴对象,然后使用ax 参数告诉pandas 要在哪些轴上绘图。最后,使用matplotlib(或图)保存图。

      import pandas as pd
      import numpy as np
      import matplotlib.pyplot as plt
      
      # Sample Data (3 groups, normally distributed)
      df = pd.DataFrame({'gp': np.random.choice(list('abc'), 1000),
                         'data': np.random.normal(0, 1, 1000)})
      

      fig, ax = plt.subplots()
      df.groupby('gp').hist(ax=ax, ec='k', grid=False, bins=20, alpha=0.5)
      fig.savefig('your_fig.png', dpi=200)
      

      your_fig.png

      【讨论】:

      • 这是我将采取的方法。您也可以直接在对象上调用savefig,例如fig.savefig('your_fig.png') 如果您希望避免同时使用 oop 和状态机
      • 您好,我尝试输入此代码,但显示 fig 未定义。
      • 我终于让它工作了。你是对的,我确实有一个错字。谢谢
      猜你喜欢
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 2017-01-25
      • 2015-07-21
      • 2022-01-14
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多