Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
preface
Matplotlib can render any graph into a variety of common file formats, such as PNG, EPS, SVG, and PDF. By default, graphics display with a minimalist user interface and can be saved to a file with a save button. However, if we need to generate a large number of graphics, this approach is not convenient, so we need to use functions to automatically save the generated graphics files. In this article, we’ll explore the file output capabilities of Matplotlib. In addition to programmatically generating file output, we’ll learn how to control output resolution and size, transparency, and more.
Generate a PNG image file
In a real-world scenario, we might want to capture the data as the program is running, but we don’t want to interrupt the execution of the program, and we want to automatically generate and save a picture for each step. Matplotlib has the flexibility to save graphics directly to image files. First, we’ll learn how to export graphics to PNG files. PNG files are ideal for bitmap output because they rely on lossless compression algorithms and can handle transparency.
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(-6.6.1024)
y = np.sinc(x)
plt.plot(x, y)
plt.savefig('sinc.png', c = 'c')
Copy the code
Tips: To save the image, simply replace the plt.show() call with the plt.savefig() call, and the view graphics window will not pop up. The function plt.savefig() works exactly the same as plt.show() — interpreting PLT commands and generating graphs, the difference being what happens at the end of the processing. The show() function sends the image data to the user interface library for presentation, while the savefig() function writes the image data to a file. While the savefig() function provides a variety of optional arguments, let’s go ahead and explore.
Control transparency
When graphics are part of a website or presentation, they may need to be displayed on top of each other. Transparency is important for such integration, and the graphics must blend into the background in an aesthetically pleasing and consistent way. To demonstrate transparency, a graphic will be created and embedded into the web page to blend in with the background of the page.
Render graphics as PNG files using a transparent background
To render the graphic as a PNG file with a transparent background, use plt.savefig() and set the optional parameter transparent to True:
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(-6.6.1024)
y = np.sinc(x)
plt.plot(x, y)
plt.savefig('sinc_1.png', c = 'c', transparent=True)
Copy the code
Make an HTML page that contains graphics
Use the PNG file saved in the previous step on the page that contains the background (background.jpg of the page background should be replaced with a file existing in the directory) :
<html>
<head>
<style>
body {
background: white url(background.jpg);
}
</style>
</head>
<body>
<img src='sinc_1.png' width='800 height='600'></img>
</body>
</html>
Copy the code
By default, plt.savefig() does not include transparency information in the output. For example, when we output a PNG image, the PNG file defaults to 24bits per pixel, and each 8bit channel stores only the red, green, and blue components of the pixel. However, when transparent output is enabled, plt.savefig() saves files 32 bits per pixel, and the additional alpha channel stores transparency information. For comparison, if we use sinc.png without the alpha channel:
<html>
<head>
<style>
body {
background: white url(background.jpg);
}
</style>
</head>
<body>
<img src='sinc.png' width='800 height='600'></img>
</body>
</html>
Copy the code
We learned from the series that we can control the graphs generated by Matplotlib with different levels of transparency by using the optional parameter alpha in plotting functions such as plt.plot, plt.Scatter, pltpie, etc. If alpha equals 1, the graph is completely opaque, which is the default; If alpha equals 0, the graph will be completely invisible.
import numpy as np
import matplotlib.pyplot as plt
name_list = ('Omar'.'Serguey'.'Max'.'Zhou'.'Abidin')
value_list = np.random.randint(99, size=len(name_list))
pos_list = np.arange(len(name_list))
plt.bar(pos_list, value_list, alpha = 75., color = 'c', align = 'center')
plt.xticks(pos_list, name_list)
plt.savefig('bar.png', transparent = True)
Copy the code
Display in AN HTML page:
<html>
<head>
<style>
body {
background: white url(background.jpg);
}
</style>
</head>
<body>
<img src='bar.png' width='800 height='600'></img>
</body>
</html>
Copy the code
Control output resolution
By default, Matplotlib automatically adjusts the output size and resolution when using bitmap images. Depending on the purpose of the bitmap image, we can also choose the resolution ourselves. For example, high resolution might be required if the image is part of a large poster, and lower resolution if you want to generate thumbnails. The plt.savefig() function provides the optional dPI argument to control the output resolution:
import numpy as np
import matplotlib.pyplot as plt
name_list = ('Omar'.'Serguey'.'Max'.'Zhou'.'Abidin')
value_list = np.random.randint(99, size=len(name_list))
pos_list = np.arange(len(name_list))
plt.bar(pos_list, value_list, alpha = 25., color = 'c', align = 'center')
plt.xticks(pos_list, name_list)
plt.savefig('bar_1.png', dpi = 300)
Copy the code
The optional parameter DPI of the Savefig () function controls the image resolution expressed in DPI(points per inch). By default, Matplotlib will output graphs in 8 x 6 space units, or a 4/3 aspect ratio. In matplotlib, 1 unit of space is equal to 100 pixels. So, by default, Matplotlib provides 800 x 600 pixel image files. If we use DPI =300, the image size is 8*300 x 6*300, which is 2400 x 1800 pixels.
We have learned how to control the aspect ratio of a graph. If you combine aspect ratio with DPI, you can have complete control over the overall scale of the image. For example, displaying a hexagon in a 512 x 512 pixel image.
import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0.2 * np.pi, 8)
points = np.vstack((np.cos(theta), np.sin(theta))).transpose()
plt.figure(figsize=(4..4.))
plt.gca().add_patch(plt.Polygon(points, color = 'c'))
plt.grid(True)
plt.axis('scaled')
plt.savefig('polygon.png', dpi = 128)
Copy the code
The above example displays the graph on a 4 x 4 unit area and outputs it at 128 dpi resolution. The output will be 512 x 512 pixels. We can also display 512 pixels in 8 x 8 units, but change the resolution to 64 dpi:
import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0.2 * np.pi, 8)
points = np.vstack((np.cos(theta), np.sin(theta))).transpose()
plt.figure(figsize=(8..8.))
plt.gca().add_patch(plt.Polygon(points, color = 'c'))
plt.grid(True)
plt.axis('scaled')
plt.savefig('polygon_1.png', dpi = 64)
Copy the code
Tips: Comments are smaller and grid lines are thinner because comments and lines have their own default values, which are expressed in units of space. Therefore, dividing the output resolution by 2 makes the comment twice as small.
Generate PDF or SVG documents
A bitmap picture represents a picture as an array of pixels of a given scale. When you zoom in, you’ll see some well-known flaws (jagged, pixel blocks, blur, etc.). Vector images, on the other hand, have scale invariance, and no matter what scale they are viewed at, details will not be lost. Therefore, sometimes we need vector images, Matplotlib can export PDF, SVG and other vector images.
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(-10.10.1024)
y = np.sinc(x)
plt.plot(x, y)
plt.savefig('sinc.pdf')
Copy the code
Tips: When plt.savefig() is called, where the file name is passed to specify whether the file is PNG, PDF or SVG, Matplotlib will infer the file type from the filename extension. In some cases, we may not want to explicitly declare the file extension. We can do this with the optional format parameter of plt.savefig. For example, by setting format=’ SVG ‘, plt.savefig does not infer the output file type from the file name passed to the function. It’s through the name passed to the format.
Series of links
Matplotlib common statistical graph drawing
Matplotlib uses custom colors to draw statistics
Matplotlib controls line style and line width
Matplotlib custom style to draw beautiful statistics
Matplotlib adds text instructions to the graph
Matplotlib adds comments to the graph
Matplotlib adds auxiliary grids and auxiliary lines to the graph
Matplotlib adds custom shapes
Matplotlib controls the scale spacing and labeling of the coordinate axes
Matplotlib uses logarithmic scales and polar coordinates
Matplotlib draws subgraphs
Matplotlib custom graph scale