Data Visualization Based on Matplotlib

Source: Internet
Author: User
Keywords matplotlib data visualization matplotlib python

Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy.

1 Basic drawing


When there are only two quantities x and y in the plot() function.

import numpy as np
import matplotlib.pyplot as plt

# Generate the x,y coordinates of each point on the curve, and then connect them with straight lines
# Use the linspace function to generate an arithmetic sequence
x = np.linspace(-np.pi, np.pi, 200)

cos_y = np.cos(x) / 2
sin_y = np.sin(x)

# Connect the points on the curve with straight lines
plt.plot(x, cos_y)
plt.plot(x, sin_y)

# Show graphics
plt.show()



Note: Basic usage of np.linspace() function


2 Line attribute setting

The attributes of the line are mainly line type, line width and color.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-np.pi, np.pi, 200)

cos_y = np.cos(x) / 2
sin_y = np.sin(x)

# Connect the points on the curve with straight lines
plt.plot(x, cos_y, linestyle='--', linewidth=1,color='dodgerblue')
plt.plot(x, sin_y, linestyle=':', linewidth=2.5,color='orangered')

plt.show()



3 Coordinate axis setting

Coordinate axis settings mainly include coordinate axis range, coordinate axis name, coordinate axis scale, cross coordinate, etc.

3.1 Get coordinate axis

Coordinate axis settings must first obtain the coordinate axis, and then operate the coordinate axis

Method to get the coordinate axis: ax = plt.gca()

gca-get current axes

Note that there are four top, bottom, left, and right axes

3.2 Get axis and operate

Get the current axis through gca first, and then operate the axis

# Get the current coordinate axis object
ax = mp.gca()
# Set the upper and right axis to none / None
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')

Of course, you can also use ax.spines to capture the bottom and left axes and operate

3.3 Specify the coordinate axis position

Change the position of the spine by set_position( (position type, amount) ); the position of the spine is determined by (position type, amount)

position type (amount)

(1) axis (0.0~1.0): put the spine on the specified axis coordinate (Axes coordinate), the range value is from 0.0 to 1.0 (corresponding coordinate from left to right); 0 means the far left, 1 means the far right, 0.5 means the middle position

(2) data (number): put spine on the specified data coordinate (data coordinate), the range value of number is related to the relationship between bottom and top, 0 indicates the position of 0 value on the coordinate axis

(3) Outward: Move the spine from the data area through the specified number of points.

(3) place the spine out from the data area by the specified number of points. (Negative values specify placing the spine inward.)

E.g

import numpy as np
import matplotlib.pyplot as mp

x = np.linspace(-np.pi, np.pi, 200) # generate an arithmetic sequence

cos_y = np.cos(x)
sin_y = np.sin(x)

ax = mp.gca()

ax.spines['left'].set_position(('axes',0.5))
ax.spines['bottom'].set_position(('data', 0))

# Set the right and top borders to be colorless
ax.spines['right'].set_color('None')
ax.spines['top'].set_color('None')

# Connect the points on the curve with straight lines
mp.plot(x, cos_y, linestyle='--', linewidth=1,color='dodgerblue')
mp.plot(x, sin_y, linestyle=':', linewidth=1.2,color='orangered')

# Show graphics
mp.show()

(A) ax.spines['bottom'].set_position(('data', 0))



(b) ax.spines['bottom'].set_position(('data', -3))



(C) ax.spines['bottom'].set_position(('data', -4))

Error thrown:

raise ValueError('bottom cannot be >= top')
ValueError: bottom cannot be >= top

Here, due to the symmetry in this case, ax.spines['bottom'].set_position(('data', 4)) where 4 and -4 are the same, and -4 is mainly used to explain the reason for the error. bottom cannot be >= top Can't figure out why.

There are two reasons for this:

(1) How is the range value (such as 4) defined? Of course, there are series values between 3 and 4, which are not enumerated here;

(2) The negative value moves down, it should be bottom -> bottom, why there is a top value (bottom cannot be >= top).

3.4 Set the coordinate axis range

Set the x-axis range: plt.xlim (minimum, maximum)

Set the y-axis range: plt.ylim (minimum, maximum)

3.5 Set the axis name

Set the x-axis name: plt.xlabel(' string str')

Set the y-axis name: plt.ylabel(' string str')

Note: If the string is Chinese, it is easy to make mistakes.

3.6 Set the coordinate axis scale

Set the x-axis scale: plt.xticks (scale label position, scale label text)

Set y-axis scale: plt.yticks (scale label position, scale label text)

3.7 Scale positioner

set_major_locator(): Set the main scale locator

set_minor_locator(): Set the minor scale locator

Common parameters

NullLocator() is empty, no tick mark

MaxNLocator() specifies the maximum number of ticks

FixedLocator() specifies the scale by parameters

AutoLocator() by default, automatically selects the most reasonable scale

IndexLocator() locates the scale according to the offset and increment

MultipleLocator() locates the scale according to the specified distance

LinearLocator() locates the scale according to the specified total number of scales

LogLocator() locates the scale according to the specified base and exponent

Specific examples

import numpy as np
import matplotlib.pyplot as plt
plt.figure('Locator')
locators = [
'plt.NullLocator()',
'plt.MaxNLocator(nbins=3,steps=[3,5,7,9])',
'plt.FixedLocator(locs=[0,2.5,5,7.5,10])',
'plt.AutoLocator()',
'plt.IndexLocator(offset=0.5, base=1.5)',
'plt.MultipleLocator()',
'plt.LinearLocator(numticks=21)',
'plt.LogLocator(base=2, subs=[1.0])']
n_locators = len(locators)
for i, locator in enumerate(locators):
plt.subplot(n_locators, 1, i + 1)
plt.xlim(0, 10)
plt.ylim(-1, 1)
plt.yticks(())
ax = plt.gca()
ax.spines['left'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_position(('data', 0))
ax.xaxis.set_major_locator(eval(locator))
ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))
plt.plot(np.arange(11), np.zeros(11))
plt.text(5, 0.3, locator[3:], ha='center', size=10)

plt.tight_layout()
plt.show()



3.8 Set the scale position

Set the x-axis scale value position (below): ax.xaxis.set_ticks_position('bottom')

Set the scale value position of the y-axis (left side): ax.yaxis.set_ticks_position('left')

Note: ax = mp.gca()

Accepted values (ACCEPTS):: ['left' |'right' |'both' |'default' |'none' | ‘top’ |'bottom']

You can also use top to position the scale value even at the top

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.