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.

Controls line style and line width

In practice, in addition to color, in most cases we also have control over graphic line styles and so on to add variety to line styles.

Line style

import numpy as np
import matplotlib.pyplot as plt
def gaussian(x, mu, sigma) :
    a = 1. / (sigma * np.sqrt(2. * np.pi))
    b = -1. / (2. * sigma ** 2)
    return a * np.exp(b * (x - mu) ** 2)
x = np.linspace(-6.6.1024)
plt.plot(x, gaussian(x, 0..1.), color = 'y', linestyle = 'solid')
plt.plot(x, gaussian(x, 0... 5), color = 'c', linestyle = 'dashed')
plt.plot(x, gaussian(x, 0..25.), color = 'm', linestyle = 'dashdot')
plt.show()
Copy the code

Tips: Use the linestyle parameter of plt.plot() to control the style of the curve. Other available line styles include “solid”, “dashed”, “dotted”, and “dashdot”. Also, the linestyle setting is not limited to plt.plot(), any graph made of lines can be used with this parameter, and the linestyle parameter can be used with any command that involves line rendering. For example, you can modify the line style of a bar chart:

import numpy as np
import matplotlib.pyplot as plt
n = 10
a = np.random.random(n)
b = np.random.random(n)
x = np.arange(n)
plt.bar(x, a, color='c')
plt.bar(x, a+b, bottom=a, color='w', edgecolor='black', linestyle = 'dashed')
plt.show()
Copy the code

Tips: since the default edgecolor is white in bar charts, pie charts, etc., to display on a white background, you need to change the edgecolor with the edgecolor parameter.

Line width

Use the lineWidth parameter to modify the line thickness. By default, lineWidth is set to 1 unit. The thickness of a line can be used to visually emphasize a particular curve.

import numpy as np
import matplotlib.pyplot as plt
def gaussian(x, mu, sigma) :
    a = 1. / (sigma * np.sqrt(2. * np.pi))
    b = -1. / (2. * sigma ** 2)
    return a * np.exp(b * (x - mu) ** 2)
x = np.linspace(-6.6.1024)
for i in range(64):
    samples = np.random.standard_normal(50)
    mu, sigma = np.mean(samples), np.std(samples)
    plt.plot(x, gaussian(x, mu, sigma), color = '75', linewidth = . 5)
plt.plot(x, gaussian(x, 0..1.), color = 'c', linewidth = 3.)
plt.show()
Copy the code

Series of links

Matplotlib common statistical graph drawing

Matplotlib uses custom colors to draw statistics