python matplotlib:如何自动保存.fig格式的数字?

时间:2014-04-15 15:34:57

标签: python matlab matplotlib figure

使用python matplotlib模块,我们可以使用pylab.savefig()函数来保存数字。 但是,似乎此函数不能用于以.fig格式保存数字。 .fig格式是matlab图形格式。

使用.fig格式,我们可以调整/修改数字,这就是为什么我要将数字保存为.fig格式。

那么有没有办法用python matplotlib以.fig格式保存数字?

4 个答案:

答案 0 :(得分:3)

你可以像这样挑选一个数字到磁盘

import matplotlib.pyplot as plt
import numpy as np
import pickle

# Plot
fig_object = plt.figure()
x = np.linspace(0,3*np.pi)
y = np.sin(x)
plt.plot(x,y)
# Save to disk
pickle.dump(fig_object,file('sinus.pickle','w'))

然后从磁盘加载并显示:

fig_object = pickle.load(open('sinus.pickle','rb'))
fig_object.show()

答案 1 :(得分:1)

如果您希望将 python 图保存为交互式图形以修改并与其他人共享,例如 MATLAB .fig 文件,那么您可以尝试以下代码。这里 z_data.values 只是一个 numpy ndarray,因此您可以使用相同的代码来绘制和保存您自己的数据。那么就不需要使用熊猫了。

这里生成的文件可以被任何有或没有 python 的人打开和交互修改,只需点击它并在 Chrome/Firefox/Edge 等浏览器中打开。

import plotly.graph_objects as go
import pandas as pd

z_data=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/api_docs/mt_bruno_elevation.csv')

fig = go.Figure(data=[go.Surface(z=z_data.values)])

fig.update_layout(title='Mt Bruno Elevation', autosize=False,
                  width=500, height=500,
                  margin=dict(l=65, r=50, b=65, t=90))

fig.show()
fig.write_html("testfile.html")

答案 2 :(得分:1)

MATLAB .fig 文件 is nothing more than a MAT-file 包含图中的每个句柄图形对象,以及它们的所有属性。 MATLAB 句柄图形对象是类对象,其类型决定了要绘制的图形,其属性决定了如何绘制。

例如,线图将有一个图形对象,包含一个轴对象,包含一个线对象。线对象将具有包含绘制数据的 ydataimport android.Manifest import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothManager import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.os.Looper import android.util.Log import android.widget.Toast import androidx.annotation.RequiresApi import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.google.android.gms.location.* @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR2) class DeviceScanActivity : AppCompatActivity() { //Getting BluetoothAdapter from BluetoothManager private fun PackageManager.missingSystemFeature(name: String): Boolean = !hasSystemFeature(name) private var fusedLocationProvider: FusedLocationProviderClient? = null private val locationRequest: LocationRequest = LocationRequest.create().apply { interval = 30 fastestInterval = 10 priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY maxWaitTime= 60 } private var locationCallback: LocationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { val locationList = locationResult.locations if (locationList.isNotEmpty()) { val location = locationList.last() Toast.makeText(this@DeviceScanActivity, "Got Location: " + location.toString(), Toast.LENGTH_LONG).show() } } } private val bluetoothAdapter: BluetoothAdapter? by lazy(LazyThreadSafetyMode.NONE) { val bluetoothManager = getSystemService(BLUETOOTH_SERVICE) as BluetoothManager bluetoothManager.adapter } companion object { const val TAG: String = "Log" private const val MY_PERMISSIONS_REQUEST_LOCATION = 99 } private val BluetoothAdapter.isDisabled: Boolean get() = !isEnabled private val REQUEST_ENABLE_BT = 1000 //On memory @RequiresApi(Build.VERSION_CODES.LOLLIPOP) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d(TAG, "DeviceScanActivity()") fusedLocationProvider = LocationServices.getFusedLocationProviderClient(this) checkLocationPermission() packageManager.takeIf { it.missingSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE) }?.also { Toast.makeText(this, "R.string.ble_not_supported", Toast.LENGTH_SHORT).show() finish() } bluetoothAdapter?.takeIf { it.isDisabled }?.apply { val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE) startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT) } finish() } override fun onResume() { super.onResume() if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { fusedLocationProvider?.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper()) } } override fun onPause() { super.onPause() if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { fusedLocationProvider?.removeLocationUpdates(locationCallback) } } private fun checkLocationPermission() { if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) { if(ActivityCompat.shouldShowRequestPermissionRationale( this, Manifest.permission.ACCESS_FINE_LOCATION ) ) { AlertDialog.Builder(this) .setTitle("Location Permission Needed") .setMessage("This app needs the Location permission, please accept to use location functionality") .setPositiveButton( "OK" ) { _, _ -> //Prompt the user once explanation has been shown requestLocationPermission() } .create() .show() } else { requestLocationPermission() } } } private fun requestLocationPermission() { Log.d(TAG, "requestLocationPermission()") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { ActivityCompat.requestPermissions( this, arrayOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION ), MY_PERMISSIONS_REQUEST_LOCATION ) } else { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), MY_PERMISSIONS_REQUEST_LOCATION ) } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { Log.d(TAG, "result()") super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { MY_PERMISSIONS_REQUEST_LOCATION -> { // If request is cancelled, the result arrays are empty. if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (ContextCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED ) { fusedLocationProvider?.requestLocationUpdates( locationRequest, locationCallback, Looper.getMainLooper() ) } } else { Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show() } return } } } 属性。但是这些对象中的每一个都有许多需要设置的属性。例如,线条还具有颜色和宽度属性、使用哪些标记以及如何绘制这些属性等。

我们可以使用 scipy.io.savemat 在 Python 中编写一个 MAT 文件。但是生成要保存的数据将是很多工作。我们必须获取我们希望保存的图中的每个 Matplotlib 对象(它们具有与 MATLAB 相似的层次结构),并将它们的属性转换为 MATLAB 如何在它们的对象中表示它们。这将涉及对每种图形对象类型的研究,因为它们都有一组不同的属性。

编写一个函数来从 Matplotlib 图创建 .fig 文件是可能的,但不值得付出努力,IMO。保存数据并将生成绘图的 Python 脚本转换为 MATLAB 脚本以在 MATLAB 中生成等效绘图会更容易。

答案 3 :(得分:0)

我从未找到过使用.fig格式输出数字的方法,但另一种方法是将您的绘图输出为封装的后脚本(eps)。这允许在事件之后利用诸如adobe illustrator之类的程序来操纵各个绘图元素。

import matplotlib.pyplot as plt
.
.
.
plt.savefig("MyFigure.eps", format="eps")