SoFunction
Updated on 2024-11-12

Examples of line, scatter, bar, histogram, and pie charts using Matplotlib

I. Line graphs

Statistical charts that represent changes in the number of statistics by rising or falling lines.

Features:Ability to show trends in data that reflect how things are changing (change)

function:(x, y)

import  as plt
import random
from pylab import mpl
["-serif"] = ["SimHei"]   # Setting up the display of Chinese fonts
["axes.unicode_minus"] = False   # Setting the normal display symbols
# Data preparation
x = range(24)   
y = [(13, 20) for i in x]   # (): randomly generate floating point numbers in the range 13-20
(figsize=(10, 5), dpi=80)   # Create a canvas
(x, y, color='y', linestyle='-',label='Camphor')   # Plotting line graphs
x_ticks_label = ["{}:00".format(i) for i in x]   # Construct x-axis scale labels
y_ticks = range(40)   # Construct y-axis scales
# Modify the scale display for x,y axis coordinates.
(x[::2], x_ticks_label[::2])
(y_ticks[10:20:1])
(True, linestyle='-', alpha=0.9)   # Add grid
(loc=0)   # Show legend
# Description information
("Time.")
("Temperature.")
("Graph of temperature changes over a 24-hour period.", fontsize=18)
("./")  # Saved to a specified location
()  # Show image

The results are as follows

II. Scatterplot

Use two sets of data to form multiple coordinate points, examine the distribution of the coordinate points, determine whether there is some kind of correlation between the two variables or summarize the distribution pattern of the coordinate points.

Features:Determine if there is a trend in quantitative correlation between variables and demonstrate outliers (distribution patterns)

function:(x, y)

import  as plt
import random
# Data preparation
x = range(100)   
y = [(13, 20) for i in x]   # (): randomly generate floating point numbers in the range 13-20
(figsize=(10, 5), dpi=80)   # Create a canvas
(x, y, color='r', linestyle='-',label='Camphor')   # Plotting line graphs
x_ticks_label = ["{}sky".format(i) for i in x]   # Construct x-axis scale labels
y_ticks = range(25)   # Construct y-axis scales
# Modify the scale display for x,y axis coordinates.
(x[::10], x_ticks_label[::10])
(y_ticks[10:22:2])
(True, linestyle='-', alpha=0.9)   # Add grid
(loc=0)   # Show legend
# Description information
("Time/day")
("Temperature.")
("Graph of temperature changes over a 24-hour period.", fontsize=18)
("./")  # Saved to a specified location
()  # Show image

The results are as follows

III. Bar charts

Data arranged in columns or rows of a worksheet can be plotted in a bar chart.

Features:Plotting discrete data, being able to see at a glance the magnitude of individual data, and comparing differences between data (statistics/comparisons).

function:(x, width, align='center', **kwargs)

  • x: data to be passed
  • width: width of the bar chart
  • align: the positional alignment of each histogram
  • **kwargs
  • color: select the color of the bar chart
import  as plt
import random
# Data preparation
x = range(0,10)   
y = [(35, 45) for i in x]   # (): randomly generate floating point numbers in the range 13-20
(figsize=(10, 5), dpi=80)   # Create a canvas
(x, y, width=0.5, color=['b','r','g','y','c','m','y','k','c','g'])   # Plotting line graphs
x_ticks_label = ["21{}classifier for school classes or grades".format(i) for i in x]   # Construct x-axis scale labels
y_ticks = range(55)   # Construct y-axis scales
# Modify the scale display for x,y axis coordinates.
(x[::1], x_ticks_label[::1])
(y_ticks[0:55:5])
(True, linestyle=':', alpha=0.3)   # Add grid
# Description information
("Class.")
("Number of persons")
("Class Size Bar Chart for Class of 2021.", fontsize=18)
("./")  # Saved to a specified location
()  # Show image

The results are as follows

IV. Histograms

A series of longitudinal stripes or lines of varying heights representing the distribution of the data, usually with the horizontal axis representing the range of the data and the vertical axis representing the distribution.

Features:Plotting continuous data to show the distribution of one or more sets of data (statistics)

function:(x, bins=None)

  • x:Data to be transmitted
  • bins:group distance
import  as plt
import numpy as np
('_mpl-gallery')
# Generate data
(1)   # Random number seed for generating random numbers
x = 4 + (0, 1.5, 200) 
# (loc=0.0, scale=1.0, size=None) for a normal distribution
# loc(float): the mean value, which corresponds to the center of the distribution. loc=0 indicates a normal distribution with the y-axis as the axis of symmetry.
# scale(float): standard deviation, corresponding to the width of the distribution, the larger the scale the shorter and fatter, the smaller the scale, the leaner and taller
# size(int or integer tuple): the value of the output is assigned to the shape, default is None.
# plot:
fig, ax = ()
(x, bins=8, linewidth=0.5, edgecolor="white")
(xlim=(0, 10), xticks=(1, 10),
       ylim=(0, 56), yticks=(0, 56, 9)) # 9, containing 0, spaced at 7, 7 x 8 = 56, i.e. [0,7,14,21,28,35,42,49,56]
# (): return a fixed-step permutation with an end and a start point
# (start, stop, num): used to create an isomorphic series, num is the number
()

The results are as follows

V. Pie charts

It is used to indicate the percentage of different classifications, and to compare various classifications by radian size

Features:Share of disaggregated data (percentage)

(x, labels=,autopct=,colors)

  • x: quantity, automatically calculated as a percentage
  • labels: name of each part
  • autopct: duty cycle display specified %1.2f%%
  • colors: each part color
  • startangle: the angle at which to start drawing.
  • shadow=True: shadow
import  as plt
# Pie chart where slices will be sorted and plotted in counterclockwise order:
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 20]
explode = (0, 0.1, 0, 0)  # Decompose only the second slice with a spacing of 0.1
fig1, ax1 = ()
(sizes, explode=explode, labels=labels, autopct='%1.3f%%',colors=['r','y','c','g'], 
        shadow=True, startangle=90)
('equal')  # Equal aspect ratios ensure that the pie is drawn in a circle
()

The results are as follows

Matplotlib official website:/stable/

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.