2019年6月30日 星期日

[ Py DS ] Ch4 - Visualization with Matplotlib (Part6)

Customizing Matplotlib: Configurations and Stylesheets 
Matplotlib’s default plot settings are often the subject of complaint among its users. While much is slated to change in the 2.0 Matplotlib release, the ability to customize default settings helps bring the package in line with your own aesthetic preferences. Here we’ll walk through some of Matplotlib’s runtime configuration (rc) options, and take a look at the newer stylesheets feature, which contains some nice sets of default configurations. 

Plot Customization by Hand 
Throughout this chapter, we’ve seen how it is possible to tweak individual plot settings to end up with something that looks a little bit nicer than the default. It’s possible to do these customizations for each individual plot. For example, here is a fairly drab default histogram (Figure 4-81): 
  1. import matplotlib.pyplot as plt  
  2. import numpy as np  
  3. %matplotlib inline  
  4. plt.style.use('classic')  
  5.   
  6. x = np.random.randn(1000)  
  7. plt.hist(x);  
Figure 4-81. A histogram in Matplotlib’s default style 

We can adjust this by hand to make it a much more visually pleasing plot, shown in Figure 4-82: 
  1. # use a gray background  
  2. ax = plt.axes(facecolor='#E6E6E6')  
  3. ax.set_axisbelow(True)  
  4.   
  5. # draw solid white grid lines  
  6. plt.grid(color='w', linestyle='solid')  
  7.   
  8. # hide axis spines  
  9. for spine in ax.spines.values():  
  10.     spine.set_visible(False)  
  11.   
  12. # hide top and right ticks  
  13. ax.xaxis.tick_bottom()  
  14. ax.yaxis.tick_left()  
  15.   
  16. # lighten ticks and labels  
  17. ax.tick_params(colors='gray', direction='out')  
  18. for tick in ax.get_xticklabels():  
  19.     tick.set_color('gray')  
  20.   
  21. for tick in ax.get_yticklabels():  
  22.     tick.set_color('gray')  
  23.   
  24. # control face and edge color of histogram  
  25. ax.hist(x, edgecolor='#E6E6E6', color='#EE6666');  
Figure 4-82. A histogram with manual customizations 

This looks better, and you may recognize the look as inspired by the look of the R language’s ggplot visualization package. But this took a whole lot of effort! We definitely do not want to have to do all that tweaking each time we create a plot. Fortunately, there is a way to adjust these defaults once in a way that will work for all plots. 

Changing the Defaults: rcParams 
Each time Matplotlib loads, it defines a runtime configuration (rccontaining the default styles for every plot element you create. You can adjust this configuration at any time using the plt.rc convenience routine. Let’s see what it looks like to modify the rc parameters so that our default plot will look similar to what we did before. 

We’ll start by saving a copy of the current rcParams dictionary, so we can easily reset these changes in the current session: 
  1. IPython_default = plt.rcParams.copy()  
Now we can use the plt.rc function to change some of these settings: 
  1. from matplotlib import cycler  
  2. colors = cycler('color', ['#EE6666''#3388BB''#9988DD''#EECC55''#88BB44''#FFBBBB'])  
  3. plt.rc('axes', facecolor='#E6E6E6', edgecolor='none',  
  4.         axisbelow=True, grid=True, prop_cycle=colors)  
  5.   
  6. plt.rc('grid', color='w', linestyle='solid')  
  7. plt.rc('xtick', direction='out', color='gray')  
  8. plt.rc('ytick', direction='out', color='gray')  
  9. plt.rc('patch', edgecolor='#E6E6E6')  
  10. plt.rc('lines', linewidth=2)  
With these settings defined, we can now create a plot and see our settings in action (Figure 4-83): 
Figure 4-83. A customized histogram using rc settings 

Let’s see what simple line plots look like with these rc parameters (Figure 4-84): 
  1. for i in range(4):  
  2.     plt.plot(np.random.rand(10))  
Figure 4-84. A line plot with customized styles 

I find this much more aesthetically pleasing than the default styling. If you disagree with my aesthetic sense, the good news is that you can adjust the rc parameters to suit your own tastes! These settings can be saved in a .matplotlibrc file, which you can read about in the Matplotlib documentation. That said, I prefer to customize Matplotlib using its stylesheets instead. 

Stylesheets 
The version 1.4 release of Matplotlib in August 2014 added a very convenient style modulewhich includes a number of new default stylesheets, as well as the ability to create and package your own styles. These stylesheets are formatted similarly to the .matplotlibrc files mentioned earlier, but must be named with a .mplstyle extension. 

Even if you don’t create your own style, the stylesheets included by default are extremely useful. The available styles are listed in plt.style.available—here I’ll list only the first five for brevity: 
  1. plt.style.available[:5]  
Output: 
['bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight']

The basic way to switch to a stylesheet is to call: 
  1. plt.style.use('dark_background')  
But keep in mind that this will change the style for the rest of the session! Alternatively, you can use the style context manager, which sets a style temporarily: 
  1. with plt.style.context('stylename'):  
  2.     make_a_plot()  
Let’s create a function that will make two basic types of plot: 
  1. def hist_and_lines():  
  2.     np.random.seed(0)  
  3.     fig, ax = plt.subplots(12, figsize=(114))  
  4.     ax[0].hist(np.random.randn(1000))  
  5.     for i in range(3):  
  6.         ax[1].plot(np.random.rand(10))  
  7.         ax[1].legend(['a''b''c'], loc='lower left')  
We’ll use this to explore how these plots look using the various built-in styles. 

Default style 
The default style is what we’ve been seeing so far throughout the book; we’ll start with that. First, let’s reset our runtime configuration to the notebook default and see how it looks (Figure 4-85): 
  1. # reset rcParams  
  2. plt.rcParams.update(IPython_default);  
  3. hist_and_lines()  
Figure 4-85. Matplotlib’s default style 

FiveThirtyEight style 
The FiveThirtyEight style mimics the graphics found on the popular FiveThirtyEight website. As you can see in Figure 4-86, it is typified by bold colors, thick lines, and transparent axes. 
  1. with plt.style.context('fivethirtyeight'):  
  2.     hist_and_lines()  
Figure 4-86. The FiveThirtyEight style 

ggplot 
The ggplot package in the R language is a very popular visualization tool. Matplotlib’s ggplot style mimics the default styles from that package (Figure 4-87): 
  1. with plt.style.context('ggplot'):  
  2.     hist_and_lines()  
Figure 4-87. The ggplot style 

Bayesian Methods for Hackers style 
There is a very nice short online book called Probabilistic Programming and Bayesian Methods for Hackers; it features figures created with Matplotlib, and uses a nice set of rc parameters to create a consistent and visually appealing style throughout the book. This style is reproduced in the bmh stylesheet (Figure 4-88): 
  1. with plt.style.context('bmh'):  
  2.     hist_and_lines()  
Figure 4-88. The bmh style 

Dark background 
For figures used within presentations, it is often useful to have a dark rather than light background. The dark_background style provides this (Figure 4-89): 
  1. with plt.style.context('dark_background'):  
  2.     hist_and_lines()  
Figure 4-89. The dark_background style 

Grayscale 
Sometimes you might find yourself preparing figures for a print publication that does not accept color figures. For this, the grayscale style, shown in Figure 4-90, can be very useful: 
  1. with plt.style.context('grayscale'):  
  2.     hist_and_lines()  
Figure 4-90. The grayscale style 

Seaborn style 
Matplotlib also has stylesheets inspired by the Seaborn library (discussed more fully in “Visualization with Seaborn” on page 311). I’ve found these settings to be very nice, and tend to use them as defaults in my own data exploration (see Figure 4-91): 
  1. with plt.style.context('seaborn'):  
  2.     hist_and_lines()  
Figure 4-91. Seaborn’s plotting style 

With all of these built-in options for various plot styles, Matplotlib becomes much more useful for both interactive visualization and creation of figures for publication. Throughout this book, I will generally use one or more of these style conventions when creating plots. 

Supplement 
Matplotlib Doc - Style sheets reference

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...