n6_Hello Plotting World_matplotlib_plt.savefig()

     To learn programming, we often start with printing the "Hello world!" message. For graphical plots that contain all the elements from data, axes, labels, lines and ticks, how should we begin?

     This chapter gives an overview of Matplotlib's functionalities and latest features. We will guide you through the setup of the Matplotlib plotting environment. You will learn to create a simple line graph, view, and save your figures. By the end of this chapter, you will be confident enough to start building your own plots and be ready to learn about customization and more advanced techniques in the coming sections. 

Come and say "Hello!" to the world of plots!

Here is a list of topics covered in this chapter:

  • What is Matplotlib?
  • Plotting the first simple line graph
  • Loading data into Matplotlib
  • Exporting the figure

Hello Matplotlib!

     Welcome to the world of Matplotlib 2.0! Follow our simple example in the chapter and draw your first "Hello world" plot. 

What is Matplotlib?

     Matplotlib is a versatile[ˈvɜːrsətl]多功能的 Python library that generates plots for data visualization. With the numerous plot types and refined styling options available, it works well for creating professional figures for presentations and scientific publications. Matplotlib provides a simple way to produce figures to suit different purposes, from slideshows幻灯片, high-quality poster printing高质量海报打印, and animations to web-based interactive plots. Besides typical 2D plots, basic 3D plotting is also supported.

     On the development side, the hierarchical class structure and object-oriented plotting interface of Matplotlib make the plotting process intuitive and systematic. While Matplotlib provides a native graphical user interface for real-time interaction, it can also be easily integrated into popular IPython-based interactive development environments, such as Jupyter notebook and PyCharm.

What's new in Matplotlib 2.0?

     Matplotlib 2.0 features many improvements, including the appearance of default styles, image support, and text rendering speed. We have selected a number of important changes to highlight later. The details of all new changes can be found on the documentation site at https://matplotlib.org/stable/users/whats_new.html.

     If you are already using previous versions of Matplotlib, you may want to pay more attention to this section to update your coding habits. If you are totally new to Matplotlib or even Python, you may jump ahead to start using Matplotlib first and revisit here later.

Changes to the default style

     The most prominent change to Matplotlib in version 2.0 is to the default style. You can find the list of changes here: https://matplotlib.org/stable/users/dflt_style_changes.html.

Color cycle

     For quick plotting without having to set colors for each data series, Matplotlib uses a list of colors called the default property cycle, whereby each series is assigned one of the default colors in the cycle. In Matplotlib 2.0, the list has been changed from the original red, green, blue, cyan, magenta, yellow, and black, noted as ['b', 'g', 'r', 'c', 'm', 'y', 'k'], to the current category10 color palette introduced by the Tableau software. As implied by the name, the new palette has 10 distinct colors suitable for categorical display. The list can be accessed by importing Matplotlib and calling matplotlib.rcParams['axes.prop_cycle'] in Python(default: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])).

To restore the old color cycle use

from cycler import cycler

mpl.rcParams['axes.prop_cycle'] = cycler(color='bgrcmyk')

Colormap

    Colormaps are useful in showing gradient渐变. The yellow to blue "viridis" colormap is now the default one in Matplotlib 2.0. This perceptually uniform colormap better represents the transition of numerical values visually than the classic “jet” scheme. This is a comparison between two colormaps:

     Besides defaulting to a perceptually continuous colormap, qualitative colormaps are now available for grouping values into categories:

Scatter plot

     Points in a scatter plot have a larger default size and no longer have a black edge, giving clearer visuals. Different colors in the default color cycle will be used for each data series if the color is not specified:

Legend

     While previous versions set the legend in the upper-right corner, Matplotlib 2.0 sets the legend location as "best" by default. It automatically avoids overlapping of the legend with the data. The legend box also has rounded corners, lighter edges, and a partially transparent background to keep the focus of the readers on the data. By default, the number of points displayed in a legend is now 1:

The previous defaults can be restored by setting:

mpl.rcParams['legend.fancybox'] = False
mpl.rcParams['legend.loc'] = 'upper right'
mpl.rcParams['legend.numpoints'] = 2
mpl.rcParams['legend.fontsize'] = 'large'
mpl.rcParams['legend.framealpha'] = None
mpl.rcParams['legend.scatterpoints'] = 3
mpl.rcParams['legend.edgecolor'] = 'inherit'

Line style

     Dash patterns in line styles can now scale with the line width to display bolder dashes for clarity:

  • the default linewidth increased from 1 to 1.5
  • the dash patterns associated with '--'':', and '-.' have changed
  • the dash patterns now scale with line width

 

 The previous defaults can be restored by setting:

mpl.rcParams['lines.linewidth'] = 1.0
mpl.rcParams['lines.dashed_pattern'] = [6, 6]
mpl.rcParams['lines.dashdot_pattern'] = [3, 5, 1, 5]
mpl.rcParams['lines.dotted_pattern'] = [1, 3]
mpl.rcParams['lines.scale_dashes'] = False

Patch edges and color

     Just like the dots in the scatter plot shown before, most filled elements no longer have a black edge by default, making the graphics less cluttered[ˈklʌtərd]使凌乱 :

 The previous defaults can be restored by setting:

mpl.rcParams['patch.force_edgecolor'] = True
mpl.rcParams['patch.facecolor'] = 'b'

Fonts

Normal text

     The default font has changed from "Bitstream Vera Sans" to "DejaVu Sans". DejaVu Sans has additional international and math characters, but otherwise has the same appearance as Bitstream Vera Sans. Latin, Greek, Cyrillic, Armenian, Georgian, Hebrew, and Arabic are all supported (but right-to-left rendering is still not handled by matplotlib). In addition, DejaVu contains a sub-set of emoji[ɪˈmoʊdʒi]表情符号 symbols.

Math text

     The default math font when using the built-in math rendering engine (mathtext) has changed from "Computer Modern" (i.e. LaTeX-like) to "DejaVu Sans". This change has no effect if the TeX backend is used (i.e. text.usetex is True).
vs

Improved functionality or performance

     Matplotlib 2.0 presents new features that improve the user experience, including speed and output quality as well as resource usage. 

Improved color conversion API and RGBA support

     The alpha channel, which specifies the degree of transparency, is now fully supported in Matplotlib 2.0. The main public functions are is_color_like(), matplotlib.colors.to_rgba(), matplotlib.colors.to_rgba_array() and to_hex(). RGBA quadruplets are encoded in hex format as "#rrggbbaa".

     A side benefit is that the Qt options editor now allows setting the alpha channel of the artists as well.https://matplotlib.org/stable/users/prev_whats_new/whats_new_2.0.0.html

Improved image support

     Matplotlib 2.0 now resamples images with less memory and less data type conversion.

Faster text rendering

     It is claimed that the speed of text rendering by the Agg backend is increased by 20%. We will discuss more on backends in Chapter 9, Adding Interactivity and Animating Plots. 

Change in the default animation codec

     To generate a video output of animated plots, a more efficient codec, H.264, is now used by default in place of MPEG-4. As H.264 has a higher compression rate, the smaller output file size permits longer video record time and reduces the time and network data needed to load them. Real-time playback of H.264 videos is generally more fluent and in better quality than those encoded in MPEG-4.  It can be set via the animation.codec rcParam.

Changes in settings

     Some of the settings are changed in Matplotlib v2.0 for convenience or consistency, or to avoid unexpected results.

New configuration parameters (rcParams)

     New parameters are added, such as date.autoformatter.year for date time string formatting.

https://matplotlib.org/stable/users/prev_whats_new/whats_new_2.0.0.html#change-in-the-default-animation-codec

Style parameter blacklist

     Style files are no longer allowed to configure settings unrelated to the style to prevent unexpected consequences. These parameters include the following: 

'interactive', 'backend', 'backend.qt4', 'webagg.port',
'webagg.port_retries', 'webagg.open_in_browser', 'backend_fallback',
'toolbar', 'timezone', 'datapath', 'figure.max_open_warning',
'savefig.directory', tk.window_focus', 'docstring.hardcopy'

Change in Axes property keywords

     The Axes properties axisbg and axis_bgcolor are replaced by facecolor to keep the keywords consistent.

Saving the figure

     If you want to both view the image on screen and save it in file, remember to call pyplot.savefig() before pyplot.show() to make sure you don't save a blank canvas.

Setting the output format

     The pyplot.savefig() function takes the path of the output file and automatically outputs it in the specified extension. For example, pyplot.savefig('output.png') will generate a PNG image. If no extension is specified, an SVG image will be generated by default. If the specified format is unsupported, let's say .doc, a ValueError Python exception will be thrown/

PNG (Portable Network Graphics)

     Compared to JPEG, another common image file format, PNG, has the advantage of allowing a transparent background. PNG is widely supported by most image viewers and handlers. 

PDF (Portable Document Format)

     A PDF is a standard document format, which you don't have to worry about the availability of readers. However, most Office software do not support the import of PDF as image.

SVG (Scalable Vector Graphics)

     SVG is a vector graphics format that can be scaled without losing details. Hence, better quality can be achieved with a smaller file size. It goes well on the web with HTML5. It may not be supported by some primitive image viewers.

Post (Postscript)

     Postscript is a page description language for electronic publishing. It is useful for batch processing images to publish.

     The Gimp Drawing Kit (GDK) raster graphics rendering is deprecated in 2.0, which means image formats such as JPG and TIFF are no longer supported with the default backend. We will discuss the backends later in more detail.

Adjusting the resolution

     Resolution measures the details recorded in an image. It determines how much you can enlarge your image without losing details. An image with higher resolution retains high quality at larger dimensions but also has a bigger file size.

     Depending on the purpose, you may want to output your figures at different resolutions. Resolution is measured as the number of color pixel dot per inch (dpi). You may adjust the resolution of a figure output by specifying the dpi parameter in the pyplot.savefig() function, for example, by:

plt.savefig('output.png',dpi=300)

     While a higher resolution delivers better image quality, it also means a larger file size and demands more computer resources. Here are some references for how high should you set your image resolution:

  • Slideshow presentations: 96 dpi+

     Here are some suggestions by Microsoft for graphics resolution for Powerpoint presentations for different screen sizes: https://docs.microsoft.com/en-us/office/troubleshoot/powerpoint/change-export-slide-resolution

 

  • Poster presentation: 300 dpi+
  • Web: 72 dpi+ (SVG that can scale responsively is recommended)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值