【问题标题】:Saving a plot in python creates only an empty pdf document在 python 中保存绘图只会创建一个空的 pdf 文档
【发布时间】:2014-08-16 19:28:06
【问题描述】:

我正在使用matplotlib官方页面http://matplotlib.org/examples/api/barchart_demo.html中存在的示例代码

#!/usr/bin/env python
# a bar plot with errorbars
import numpy as np
import matplotlib.pyplot as plt

N = 5
menMeans = (20, 35, 30, 35, 27)
menStd =   (2, 3, 4, 1, 2)

ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd)

womenMeans = (25, 32, 34, 20, 25)
womenStd =   (3, 5, 2, 3, 3)
rects2 = ax.bar(ind+width, womenMeans, width, color='y', yerr=womenStd)

# add some
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') )

ax.legend( (rects1[0], rects2[0]), ('Men', 'Women') )

def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)

plt.show()

此图显示完全正确。 但是,如果我想保存它,在代码底部使用以下命令,它不会保存绘图。

plt.savefig("result.pdf")

是不是我做错了什么?

【问题讨论】:

    标签: python pdf matplotlib charts pdf-generation


    【解决方案1】:

    plt.savefig("result.pdf") 行移到plt.show() 之前应该会将绘图正确地保存为pdf 文件。

    您可能正在使用交互式后端。在plt.show() 之后,会弹出一个包含绘图的窗口。如果您随后关闭窗口,情节就消失了(类似于plt.close() 调用)。因此,如果您在关闭绘图窗口后这样做,plt.savefig() 将无法保存任何内容。

    【讨论】:

    • 哦!!!确实是的!非常感谢CT!但是对我来说很奇怪,为什么显示图表和保存图表的顺序很重要?我的意思是,它们应该是两个独立的动作......
    • 不客气。 plt.show() 是一个 阻塞 函数,如果 savefig() 在它之后,则在窗口关闭之前不会执行。但是,你看,一旦窗口关闭,情节就消失了,没有任何东西可以保存。
    【解决方案2】:

    感谢您的澄清,它也对我有用。我正在绘制一个实时数据,所以我必须将它包含在循环中,然后它就可以工作了。

    定义动画(i): 全局参数1 路径 = 'C:/Python36/Somendra/' + arg1 +'.csv' 名称 = arg1 + '.csv' 拉数据=打开(路径,“r”) dataArray = csv.reader(pullData, delimiter=',') xar = [] 亚尔 = [] 对于 dataArray 中的行: xar.append(行[0]) yar.append(行[1]) #ax1.clear() 标签 =[z 范围内的 z(len(xar))] ax1.plot(标签,yar) #ax1.plot(xar,yar) ax1.set_xticks(标签) ax1.set_xticklabels(xar, rotation='vertical', fontsize=10) plt.savefig('fig11.png')

    如果 name =="ma​​in": arg1 = str(sys.argv[1])

    style.use('fivethirtyeight')
    fig = plt.figure(figsize=(8,6))
    ax1 = fig.add_subplot(1,1,1)
    time.sleep(1)
    plt.grid(True)
    ani = animation.FuncAnimation(fig, animate, interval=1000)
    #plt.savefig('fig11.png')
    plt.show() 
    

    【讨论】:

      猜你喜欢
      • 2018-11-29
      • 2023-04-07
      • 2012-07-04
      • 2011-12-02
      • 1970-01-01
      • 2020-07-27
      • 2017-03-01
      • 1970-01-01
      相关资源
      最近更新 更多