Drawing summary of python matplotlib and networkx

1, matplotlib

Matplotlib is the most widely used 2D graphic drawing library in Python. Learning the usage of Matplotlib well can help us show the state of various data more flexibly in statistical analysis. It can be used together with NumPy.

1. How to create

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

2. Picture size

plt.figure(figsize=(9, 3))  # Image size: length and width

3. Title

plt.title("Abnormal point")

4. Fractograph

plt.figure(1, figsize=(9, 3))  # Figure 1
plt.figure(2, figsize=(9, 3))  # Figure 2
plt.figure(3, figsize=(9, 3))  # Figure 3
plt.figure(4, figsize=(9, 3))  # Figure 4

5. Subgraph

# Matrix arrangement - two rows and two columns
plt.subplot(2, 2, 1)  # Subgraph 1
plt.subplot(2, 2, 2)  # Subgraph 2
plt.subplot(2, 2, 3)  # Subgraph 3
plt.subplot(2, 2, 4)  # Subgraph 4

6. subplot with main title and subtitle?  

# There is the function "title", which is used to generate the general title
plt.suptitle('Main titile', fontsize=14) 
plt.subplot(2, 2, 1)
plt.title('subtitle1')  # Title of sub Figure 1
plt.subplot(2, 2, 2)
plt.title('subtitle2')  # Title of sub Figure 2
plt.subplot(2, 2, 3)
plt.title('subtitle3')  # Title of sub Figure 3
plt.subplot(2, 2, 4)
plt.title('subtitle4')  # Title of sub Figure 4

7. Another subplot method

fig, ax_arr = plt.subplots(4, sharex=True)
fig.set_size_inches(12, 8)
pd.Series(data=y, index=x).plot(ax=ax_arr[0], color="b", linestyle='-')
ax_arr[0].set_title("Original sequence")

pd.Series(data=decompose_model.trend, index=x).plot(ax=ax_arr[1], color="c", linestyle='-')
ax_arr[1].set_title("Trend section")
pd.Series(data=decompose_model.seasonal, index=x).plot(ax=ax_arr[2], color="g", linestyle='-')
ax_arr[2].set_title("Seasonal section")
pd.Series(data=decompose_model.resid, index=x).plot(ax=ax_arr[3], color="r", linestyle='-')
ax_arr[3].set_title("Residual section")

8. Sub graph merges a graph, do not know quantity

lens = len(all_sub_graphs)
b = a = int(math.sqrt(lens))
if a*a < lens:
    b = b+1
plot = plt.subplot(a, b, i+1)

9. Line color and type

plt.plot(y, color='b', marker='o')
plt.plot(y, color='b', linestyle='-')

linestyle, marker optional parameter reference: https://www.cnblogs.com/darkknightzh/p/6117528.html

10. matplotlib remove axis scale


11. The legend of label is in Chinese

plt.rcParams['font.sans-serif']=['SimHei']  # Used to display Chinese labels normally
plt.rcParams['axes.unicode_minus']=False    # Used to display negative sign normally
# In case of Chinese, you need u 'content'

12. Set axis

ax = plt.gca()
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title', fontsize=fontsize)
ax.set_xlim(xmin, xmax)  # Set axis range

13. Random color

def random_color():
    color_arr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
    color = ""
    for i in range(6):
        color += color_arr[random.randint(0, 14)]
    return "#"+color

14. Legend location

plt.legend(handles = [l1, l2], labels = ['a', 'b'], loc = 'best')

In addition to 'best', the loc attributes are: 'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center'

15. Solve the Chinese confusion of linux pictures

plt.rcParams['font.sans-serif'] = ['simhei']  # Used to display Chinese labels normally

Not yet:

import os
from matplotlib import font_manager as fm, rcParams

fig, ax = plt.subplots()
fpath = os.path.join(rcParams["datapath"], "D:/Anaconda3/Lib/site-packages/matplotlib\mpl-data/fonts/ttf/simhei.ttf")  # Need to set up font library in advance
prop = fm.FontProperties(fname=fpath)
fname = os.path.split(fpath)[1]
ax.set_title(u'Chinese out This is a special font: {}'.format(fname), fontproperties=prop)
ax.set_xlabel('This In a hurry the default font', fontproperties=prop)


plt.legend(loc="best", prop=prop)

16. Draw a vertical dotted line

  • vlines(x, ymin, ymax)
  • hlines(y, xmin, xmax)
plt.vlines(x-values, -5, 100, colors="#808080", linestyles="dashed", label="baseline")

plt.hlines(up_threshold, x[0], x[-1], colors="r", linestyles="dashed")   # go online
plt.hlines(low_threshold, x[0], x[-1], colors="r", linestyles="dashed")  # Offline

19. Histogram drawing

plt.hist(data, color='b', alpha=.7)

18. The drawing method of legend outside the figure

ax1 = plt.gca()
box = ax1.get_position() 
ax1.set_position([box.x0, box.y0, box.width, box.height* 0.8])
ax1.legend(loc='center left', bbox_to_anchor=(0.2, 1.12), ncol=3)

19,tight_layout adjust subgraph parameters

tight_layout will automatically adjust the parameters of subgraphs, adjust the spacing between subgraphs to reduce the stacking, so that it fills the entire image area. Key parameters pad, w_pad or h_pad, the extra margin between these parameter image boundaries and subgraphs. Margins are specified in font size units.

plt.tight_layout(pad=0.5, w_pad=0.5, h_pad=2.0)

20. Picture output mode

plt.savefig("fig.png")  # Output mode 1: save the image as a png image file
plt.show()              # Output mode 2: display this image in the window
tight_layout in plt.savefig The call mode of is relatively stable. We will plt.show() replace function with plt.savefig Function, after replacement, another png image will be added locally, and the whole image area will be filled by the subgraph of the image.
plt.savefig('fig.png', bbox_inches='tight') # Replace plt.show()

2, networkx

networkx is a graph theory and complex network modeling tool developed with Python language. It has built-in common graph and complex network analysis algorithm, which can facilitate the complex network data analysis, simulation modeling and other work.
Using networkx, we can store network in standardized and non standardized data format, generate many kinds of random network and classic network, analyze network structure, build network model, design new network algorithm, and draw network.
networkx supports the creation of simple undirected graphs, digraphs and multigraph s; many standard graph theory algorithms are built in, and the nodes can be arbitrary data; any boundary value dimension is supported, which has rich functions and is easy to use.
Network x takes graph as the basic data structure. The graph can be generated by program, online data source, and read from file and database.


Tags: network Python Linux Database

Posted on Sun, 14 Jun 2020 02:22:51 -0400 by faraco