Matplotlib 简明教程
Matplotlib - PostScript
PostScript 是一种页面描述语言和动态类型的基于堆栈的编程语言,通常缩写为 PS。它由 Adobe Systems 于 20 世纪 80 年代初创建,其主要目的是用来描述已打印页面的布局和图像。该语言广泛用于电子出版和桌面出版应用程序中。
PostScript is a page description language and a dynamically typed, stack-based programming language often abbreviated as PS. Created by Adobe Systems in the early 1980s, its primary purpose is to describe the layout and graphics of printed pages. It is widely used in electronic publishing and desktop publishing applications.
一个 PostScript 文件可以打印出来或显示在不同设备上,而不会失真。这是用于不同目的生成图表时的主要优势。
A PostScript file can be printed or displayed on different devices without losing quality. This is the key advantage when generating plots for different purposes.
PostScript in Matplotlib
在 Matplotlib 的上下文中,PostScript 作为 backend rendering engine (用于在屏幕上显示图形或写入文件),使用户能够生成出版质量的图表和图像。当您选择 PostScript 后端时,Matplotlib 会生成 PostScript 代码来描述图表布局和外观。
In the context of Matplotlib, PostScript serves as a backend rendering engine (used for displaying figures on the screen or writing to files), enabling users to generate publication-quality plots and graphics. When you choose the PostScript backend, Matplotlib generates PostScript code to describe the layout and appearance of the plot.
由 Matplotlib 生成的 PostScript 代码包括在页面上绘制线条、形状、文本以及其他图像元素的指令。这些指令由 PostScript 编程语言编写。
The PostScript code generated by Matplotlib includes instructions for drawing lines, shapes, text, and other graphical elements on a page. These instructions are written in the PostScript programming language.
Matplotlib PostScript 后端 ( matplotlib.backends.backend_ps ) 可以生成 .ps 和 .eps 文件。
The Matplotlib PostScript Backend (matplotlib.backends.backend_ps) can produce both .ps and .eps files.
Create a PostScript file
让我们使用 Matplotlib 探究如何创建简单绘图并将其作为 PostScript 文件保存。
Let’s explore how to create a simple plot and save it as a PostScript file using Matplotlib.
Example 1
此示例演示如何创建带有换行文本的简单绘图并将其作为 PostScript 文件 (.ps) 保存。
This example demonstrates how to create a simple plot with wrapped text and saves it as a PostScript file(.ps).
import matplotlib
import matplotlib.pyplot as plt
import textwrap
from pylab import *
# Generate a string containing printable characters (ASCII 32 to 126)
text_to_wrap = "".join(c for c in map(chr, range(32, 127)) if c.isprintable())
# Wrap the string to fit within the figure
wrapped_text = "\n".join(textwrap.wrap(text_to_wrap))
# Add the wrapped text to the figure
figtext(0, 0.5, wrapped_text)
# Save the figure to a PostScript file named "test.ps"
savefig("test.ps")
print('Successfully created the PostScript (PS) file...')
如果您访问输出所保存的文件夹,您可以观察到名为 test.ps 的结果 PostScript 文件。
If you visit the folder where the Output is saved you can observe resultant PostScript file named test.ps.
Successfully created the PostScript (PS) file...
Example 2
此为另一个演示如何使用 PostScript 后端来生成绘图并将其保存为封装 PostScript (EPS) 文件的示例。
Here is another example that demonstrates how to use the PostScript backend to generate a plot and save it to an encapsulated PostScript (EPS) file.
import numpy as np
from matplotlib import pyplot as plt
# Generate data
x_data = np.linspace(1, 10, 100)
y_data = np.sin(x_data)
# Create the plot
plt.plot(x_data, y_data, c='green', marker='o')
plt.grid()
# Save the figure to a PostScript file named "example.eps"
plt.savefig("example.eps")
print('Successfully created the encapsulated PostScript (EPS) file...')
如果您访问输出所保存的文件夹,您可以观察到名为 example.eps 的结果 PostScript 文件。
If you visit the folder where the Output is saved you can observe resultant PostScript file named example.eps.
Successfully created the encapsulated PostScript (EPS) file...
Customizing PostScript Output
调整 Matplotlib 中的 PostScript 输出设置,可以提升封装 PostScript (EPS) 文件的视觉品质。默认情况下,Matplotlib 在创建 EPS 文件时使用蒸馏处理。此蒸馏步骤会移除 LaTeX 在 EPS 文件中视为非法的特定 PostScript 运算符。
Adjusting the PostScript output settings in Matplotlib allows you to enhance the visual quality of Encapsulated PostScript (EPS) files. By default, Matplotlib uses a distillation process when creating EPS files. This distillation step removes specific PostScript operators that LaTeX considers illegal in an EPS file.
一种有效的方法涉及修改分辨率参数以取得更好的视觉效果。 rcParams["ps.distiller.res"] 参数控制 EPS 文件的分辨率,默认值设为 6000。提升此值可能会导致更大的文件,但可能会显着提升视觉品质并维持合理的伸缩性。
One effective workaround involves modifying the resolution parameter to achieve better visual results. The rcParams["ps.distiller.res"] parameter controls the resolution of the EPS files, with the default value set to 6000. Increasing this value can result in larger files but may significantly improve visual quality and maintain reasonable scalability.
Example 1
此示例演示调整分辨率参数如何提升 EPS 文件的视觉品质。
This example demonstrates how adjusting resolution parameter can enhance the visual quality of EPS files.
import numpy as np
import matplotlib.pyplot as plt
# Set the resolution for EPS files
plt.rcParams["ps.distiller.res"] = 12000
# Set the figure size and enable autolayout
plt.rcParams["figure.figsize"] = [7, 3.50]
plt.rcParams["figure.autolayout"] = True
# Generate data
x_data = np.linspace(1, 10, 100)
y_data = np.sin(x_data)
# Plotting
plt.plot(x_data, y_data, label='Sine Wave', color='green')
# Save the figure as an EPS file
plt.savefig('Output customized file.eps', format='eps', bbox_inches='tight')
print('Successfully created the output customized PostScript (EPS) file...')
如果您访问输出所保存的文件夹,您可以观察到名为 Output customized file.eps 的结果 PostScript 文件。
If you visit the folder where the Output is saved you can observe resultant PostScript file named Output customized file.eps.
Successfully created the output customized PostScript (EPS) file...
Example 2
以下示例演示在 savefig() 函数中设置 transparent=True 参数时,如何将绘图作为 .eps 文件保存时保持透明性。
Here is an example that demonstrates how the transparency is preserved when saving the plot as an .eps file by setting the transparent=True parameter in the savefig() function.
import numpy as np
import matplotlib.pyplot as plt
# Adjust figure size and autolayout
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Generate data
x_data = np.linspace(1, 10, 100)
y_data = np.sin(x_data)
# Plot data with transparency
plt.plot(x_data, y_data, c='green', marker='o', alpha=.35, ms=10, lw=1)
plt.grid()
# Save plot as .eps by preserving the transparency
plt.savefig("lost_transparency_img.eps", transparent=True)
# Display plot
plt.show()
执行上述代码时,您将获得以下输出 -
On executing the above code you will get the following output −
每当以 .eps/.ps 保存绘图时,绘图的透明性就会消失。您可以在上述图像中观察到区别。
Whenever plots are saved in .eps/.ps, then the transparency of the plots get lost. You can observe the difference in th eabove image.