Ubuntu和Matplotlib

2024-09-24 00:27:34 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我使用的是来自amazonaws的ubuntuserver14.04lts(HVM),SSD卷类型实例,运行python2.7.9和最新版本的matplotlib。我试图绘制正弦函数,然后将图形保存到主目录中的png。以下是我的代码:

import matplotlib
matplotlib.use('AGG')
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2*np.pi,100)
y = np.sin(x)
plt.plot(x,y)
plt.savefig('Sine')

保存图形后,我使用WinSCP将png文件移动到本地桌面,以便打开它。但是当我打开文件时,我只看到一个黑色的方框,上面有x和y记号。在

我只是使用了错误的后端,还是问题严重得离谱?在


Tags: 文件实例import版本图形类型pngmatplotlib
1条回答
网友
1楼 · 发布于 2024-09-24 00:27:34

我相信你的问题来自于这样一个事实:你实际上没有在你的图上绘制任何东西,因为x是空的。您的np.arange中使用的步骤太大。np.arange的第三个参数是用于构建数组的步进或增量使用,与matlab linspace函数不同,后者的第三个参数是生成的点数。在

试试这个:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2*np.pi,0.01)
y = np.sin(x)
plt.plot(x,y)


plt.savefig('Sine.png')

这导致了这个png(在ubuntu15.04、Python 2.7.9、matplotlib 1.4.2中):

enter image description here

更新(2015-07-28):

关于backend,正如pyplot documentation中所建议的:

If format is None and fname is a string, the output format is deduced from the extension of the filename. If the filename has no extension, the value of the rc parameter savefig.format is used.

If fname is not a string, remember to specify format to ensure that the correct backend is used.

因此,显式地指定文件的扩展名可能有助于解决backend的问题(我已经相应地更新了代码)。默认情况下,后端TkAgg是在我的机器上使用的,所以用默认设置绘图没有问题。在

相关问题 更多 >