latex font:5 Powerful Tips for Visualizing Data with Matplotlib-Font Tutorial免费ppt模版下载-道格办公

5 Powerful Tips for Visualizing Data with Matplotlib

Data visualization is used to display data in a more direct representation and is easier to understand. It can be formed in the form of bar chart, scatter chart, line chart, pie chart, etc. Many people still use Matplotlib as a backend module to visualize their graphics. In this story, I'll give you some tips, 5 powerful tips for creating a great chart using Matplotlib.

1. Use Latex font

By default, we can use some nice fonts provided by Matplotlib. However, some symbols are not good enough and cannot be created by Matplotlib. For example, the symbol phi(φ) is shown in Figure 1.

As you can see in the y-label, it's still the symbol for phi (φ), but for some it's not enough as a plot label. To make it more beautiful, you can use Latex fonts. How to use it? The answer is here.

plt.rcParams['text.usetex'] = Trueplt.rcParams['font.size'] = 18

You can add the above code at the beginning of your python code. Line 1 defines the LaTeX font used in the drawing. You also need to define a font size larger than the default size. If you don't change it, I think it will give you a little tag. I chose 18. The result after applying the above code is shown in Figure 2.

You need to write double dollar signs at the beginning and end of the symbol, like this (\$…\$)

plt.xlabel('x')plt.ylabel('$\phi$ (phi)')

If you have some errors or do not have the required libraries installed to use LaTeX fonts, you need to install these libraries by running the following code in your Jupyter notebook.

!apt install texlive-fonts-recommended texlive-fonts-extra cm-super dvipng

If you want to install through the terminal, you can enter

apt install texlive-fonts-recommended texlive-fonts-extra cm-super dvipng

Of course, you can use some different font families, such as serif, sans-serif (example above), etc. To change the font family you can use the following code.

plt.rcParams['font.family'] = "serif"

If you add the above to your code, it will give you a graph as shown in Figure 3.

Can you understand the difference between Figure 3 and Figure 2? Yes, if you analyze carefully, the difference is in the tail of the font. The latter graphic uses serif, while the former uses sans-serif. In short, serif means tail and sans means nothing. If you want to know more about font families or fonts, I recommend you use this link.

https://en.wikipedia.org/wiki/Typeface

You can also set the font family/font using the Jupyter themes library. I've done a tutorial on using it. Just click on the link below. Jupyter Theme can also change your Jupyter theme, such as dark mode theme: https://medium.com/@rizman18/how-can-i-customize-jupyter-notebook-into-dark-mode-7985ce780f38

We wish to insert complex text, as shown in the title of Figure 4.

If you want to create Figure 4, you can use this complete code

# Import library import numpy as npimport matplotlib.pyplot as plt# Adjust matplotlib parameters plt.rcParams.update(plt.rcParamsDefault)plt.rcParams['text.usetex'] = Trueplt.rcParams['font. size'] = 18plt.rcParams['font.family'] = "serif"# Create simulated data r = 15theta = 5rw = 12gamma = 0.1err = np.arange(0., r, .1)z = np.where (err < rw, 0, gamma * (err-rw)**2 * np.sin(np.deg2rad(theta)))# Visualized data plt.scatter(err, z, s = 10)plt.title( r'$\Sigma(x) = \gamma x^2 \sin(\theta)#39;, pad = 20)plt.xlabel('x')plt.ylabel('$\phi#39;)# Save Chart plt.savefig('latex.png', dpi = 300, pad_inches = .1, bbox_inches = 'tight')

2. Create a zoom effect

In this tip, I'll give you a code that generates a plot, as shown in Figure 5.

First, you need to know about plt.axes() and plt.figure() which you can check in the link below. The codeplt.figure() covers all objects in a single container, including axes, figures, text, and labels. The codeplt.axes() only contains specific parts. I think Figure 6 can give you a simple understanding.

Use plt.figure() for the black box, and plt.axes() for the red and blue boxes. In Figure 6, there are two axes, red and blue . You can check this link for basic reference: https://medium.com/datadriveninvestor/python-data-visualization-with-matplotlib-for-absolute-beginner-python-part-ii-65818b4d96ce

After understanding this, you can analyze how to create Figure 5. Yes, simply put, there are two axes in Figure 5. The first axis is a large plot with a zoomed-in version from 580 to 650, and the second is a zoomed-out version. Below is the code that creates Figure 5.

# Create the main container fig = plt.figure()# Set the random seed np.random.seed(100)# Create simulation data x = np.random.normal(400, 50, 10_000)y = np .random.normal(300, 50, 10_000)c = np.random.rand(10_000)# Create a magnified image ax = plt.scatter(x, y, s = 5, c = c)plt.xlim(400, 500 )plt.ylim(350, 400)plt.xlabel('x', labelpad = 15)plt.ylabel('y', labelpad = 15)# Create an enlarged image ax_new = fig.add_axes([0.6, 0.6, 0.2, 0.2]) # Compare the position of the enlarged image with the proportion of the enlarged image plt.scatter(x, y, s = 1, c = c) # Save the graphic, leaving margins plt.savefig('zoom.png', dpi = 300, bbox_inches = 'tight', pad_inches = .1)

If you need an explanation of the code, you can visit this link: https://medium.com/datadriveninvestor/data-visualization-with-matplotlib-for-absolute-beginner-part-i-655275855ec8

I've also provided another version of the zoom effect that you can use with Matplotlib. As shown in Figure 7.

To create Figure 7, you need to create three axes in Matplotlib using add_subblot or other syntax (subblot). To make it easier to use, I'm adding it here. To create them, you can use the following code.

fig = plt.figure(figsize=(6, 5))plt.subplots_adjust(bottom = 0., left = 0, top = 1., right = 1)# Create the first axis, top left Use the green figure for the corner figure sub1 = fig.add_subplot(2,2,1) # Two rows and two columns, the first cell # Create the second axis, the orange axis in the upper left corner sub2 = fig.add_subplot(2, 2,2) # Two rows and two columns, the second cell # Create the third axis, the combination of the third and fourth cells sub3 = fig.add_subplot(2,2,(3,4)) # Two Row and column, merge the third and fourth cells

The code will generate a graph, as shown in Figure 8. It tells us that it will generate 2 rows and 2 columns. Axis sub1(2,2,1) is the first axis in the subplot (first row, first column). The order starts from the upper left side to the right. Axis sub2(2,2,2) is placed in the first row and second column. Axis sub3 (2, 2, (3, 4)), is the merged axis between the first column of the second row and the second column of the second row.

Of course, we need to define a mock data in order to visualize it in the plot. Here I have defined a simple combination of linear and sine functions as shown in the code below.

# Use lambda to define function stock = lambda A, amp, angle, phase: A * angle + amp * np.sin(angle + phase)# Define parameter theta = np.linspace(0., 2 * np.pi, 250) # x-axis np.random.seed(100)noise = 0.2 * np.random.random(250)y = stock(.1, .2, theta, 1.2) + noise # y-axis

If you apply the code to the previous code, you will get a graph as shown in Figure 9.

The next step is to constrain the x- and y-axes of the first and second axes (sub1 and sub2), create blocking regions for the two axes in sub3, and create a ConnectionPatch that represents the scaling effect. This can be done using the following complete code (remember, I'm not using a loop for simplicity).

# Use lambda to define function stock = lambda A, amp, angle, phase: A * angle + amp * np.sin(angle + phase)# Define parameter theta = np.linspace(0., 2 * np.pi, 250) # x-axis np.random.seed(100)noise = 0.2 * np.random.random(250)y = stock(.1, .2, theta, 1.2) + noise # y-axis# Create Main container of size 6x5 fig = plt.figure(figsize=(6, 5))plt.subplots_adjust(bottom = 0., left = 0, top = 1., right = 1)# Create the first axis, top left Use the green picture for the angle picture sub1 = fig.add_subplot(2,2,1) # Two rows and two columns, the first cell sub1.plot(theta, y, color = 'green')sub1.set_xlim(1, 2 )sub1.set_ylim(0.2, .5)sub1.set_ylabel('y', labelpad = 15)# Create the second axis, the orange axis in the upper left corner sub2 = fig.add_subplot(2,2,2) # Two lines Two columns, second cell sub2.plot(theta, y, color = 'orange')sub2.set_xlim(5, 6)sub2.set_ylim(.4, 1)# Create a third axis, third and Combination of four cells sub3 = fig.add_subplot(2,2,(3,4)) # Two rows and two columns, merge the third and fourth cells sub3.plot(theta, y, color = 'darkorchid', alpha = .7)sub3.set_xlim(0, 6.5)sub3.set_ylim(0, 1)sub3.set_xlabel(r'$\theta$ (rad)', labelpad = 15)sub3.set_ylabel('y', labelpad = 15)# Create a blocking area in the third axis sub3.fill_between((1,2), 0, 1, facecolor='green', alpha=0.2) # The blocking area in the first axis sub3.fill_between((5 ,6), 0, 1, facecolor='orange', alpha=0.2) # The blocking area of ​​the second axis # Create the ConnectionPatchcon1 of the first axis on the left = ConnectionPatch(xyA=(1, .2), coordsA= sub1.transData, xyB=(1, .3), coordsB=sub3.transData, color = 'green')# Add to the left fig.add_artist(con1)# Create the ConnectionPatch of the first axis on the right con2 = ConnectionPatch( xyA=(2, .2), coordsA=sub1.transData, xyB=(2, .3), coordsB=sub3.transData, color = 'green')# Add to the right fig.add_artist(con2)# On the left Create a second axis ConnectionPatchcon3 = ConnectionPatch(xyA=(5, .4), coordsA=sub2.transData, xyB=(5, .5), coordsB=sub3.transData, color = 'orange')# Add to Left fig.add_artist(con3)# Create a ConnectionPatch of the second axis on the right side con4 = ConnectionPatch(xyA=(6, .4), coordsA=sub2.transData, xyB=(6, .9), coordsB=sub3. transData, color = 'orange')# Add to the right fig.add_artist(con4)# Save the graphic, leaving margins plt.savefig('zoom_effect_2.png', dpi = 300, bbox_inches = 'tight', pad_inches = . 1)

The code will give you a nice zoom effect, as shown in Figure 7.

3. Create legend

Do you have many legends to display in your figure? If so, you need to place them outside the main axis.

To place the legend outside the main container, you need to adjust the position using this code

plt.legend(bbox_to_anchor=(1.05, 1.04)) #Legend position

The values ​​1.05 and 1.04 are in the x and y coordinates towards the main container. You can change it. Now, apply the above code to our code,

# Use lambda to create a wave function wave = lambda amp, angle, phase: amp * np.sin(angle + phase)# Set the parameter value theta = np.linspace(0., 2 * np.pi, 100)amp = np.linspace(0, .5, 5)phase = np.linspace(0, .5, 5)# Create the main container and its title plt.figure()plt.title(r'Wave Function $y = \gamma \sin(\theta + \phi_0) #39;, pad = 15)# Create plots for each amplifier and stage for i in range(len(amp)): lgd1 = str(amp[i]) lgd2 = str(phase[i]) plt.plot(theta, wave(amp[i], theta, phase[i]), label = (r'$\gamma = #39;+lgd1+', $\phi = # 39; +lgd2))plt.xlabel(r'$\theta$ (rad)', labelpad = 15)plt.ylabel('y', labelpad = 15)# Adjust the legend plt.legend(bbox_to_anchor=(1.05, 1.04 ))# Save the graphic, leaving margins plt.savefig('outbox_legend.png', dpi = 300, bbox_inches = 'tight', pad_inches = .1)

After running the code, it will give a graph as shown in Figure 11.

If you want to make the legend box prettier, you can use the following code to add a shadow effect. It will display a graph as shown in Figure 12.

plt.legend(bbox_to_anchor=(1.05, 1.04), shadow=True)

4. Create a continuous error plot

Over the past decade, the style of data visualization has shifted to a clean drawing theme. We can see this shift by reading some new papers in international journals or on the web. One of the most popular methods is to visualize data with continuous errors instead of using error bars. You can see it in Figure 13.

Figure 13 was generated using fill_between. In the fill_between syntax, you need to define upper and lower bounds, as shown in Figure 14.

To apply it you can use the following code.

plt.fill_between(x, upper_limit, lower_limit)

Parameter upper and lower limits are interchangeable. Here is the complete code.

N = 9x = np.linspace(0, 6*np.pi, N)mean_stock = (stock(.1, .2, x, 1.2))np.random.seed(100)upper_stock = mean_stock + np.random.randint(N) * 0.02lower_stock = mean_stock - np.random.randint(N) * 0.015plt.plot(x, mean_stock, color = 'darkorchid', label = r'$y = \gamma \ sin(\theta + \phi_0)#39;)plt.fill_between(x, upper_stock, lower_stock, alpha = .1, color = 'darkorchid')plt.grid(alpha = .2)plt.xlabel(r'$\ theta$ (rad)', labelpad = 15)plt.ylabel('y', labelpad = 15)plt.legend()plt.savefig('fill_between.png', dpi = 300, bbox_inches = 'tight', pad_inches = .1)

5. Adjust margins

If you analyze each line of code above, plt.savefig() will be followed by a complex parameter: bbox_inches and pad_inches. They provide you with margins when you are writing a journal or article. If you don't include them, the plot will have larger margins after saving. Figure 15 shows different plots with and without bbox_inches and pad_inches.

I think you can't see the difference between the two plots in Figure 15. I'll try displaying it with a different background color, as shown in Figure 16.

Likewise, this tip will help you when inserting your diagram into a paper or article. You don't need to crop it to save space.

Conclusion

Matplotlib is a multi-platform library that can be used on many operating systems. It is one of the older libraries for visualizing data, but it is still powerful. Because developers always make some updates based on the trends in data visualization. Some of the tips mentioned above are examples of newer ones.

Articles are uploaded by users and are for non-commercial browsing only. Posted by: Lomu, please indicate the source: https://www.daogebangong.com/en/articles/detail/shi-yong-Matplotlib-ke-shi-hua-shu-ju-de-5-ge-qiang-da-ji-qiao.html

Like (810)
Reward 支付宝扫一扫 支付宝扫一扫
single-end

Related Suggestion