search
HomeBackend DevelopmentPython Tutorialpython tutorial on using matplotlib to draw a line chart

Matplotlib is a Python toolbox for data visualization in scientific computing. With it, Python can draw a variety of data graphics such as Matlab and Octave. The following article mainly introduces the tutorial on how to draw a line chart using matplotlib in python. Friends in need can refer to it.

Introduction to matplotlib

matplotlib is the most famous drawing library in Python. It provides a set of command APIs similar to matlab, which is very suitable for interaction. Cartographically. And it can also be easily used as a drawing control and embedded in GUI applications.

Its documentation is quite complete, and there are hundreds of thumbnails in the Gallery page, and there are source programs after opening them. So if you need to draw a certain type of diagram, just browse/copy/paste on this page and you'll basically be done.

The more famous data graph tool under Linux is gnuplot. This is free. Python has a package that can call gnuplot, but the syntax is not familiar and the drawing quality is not high.

Matplotlib is relatively strong: Matlab’s syntax, python language, and latex’s drawing quality (you can also use mathematical formulas drawn by the built-in latex engine).

How to install the drawing library Matplotlib: Click here

matplotlib draws a line chart

1. line chart

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 100)
y1, y2 = np.sin(x), np.cos(x)

plt.plot(x, y1)
plt.plot(x, y2)

plt.title('line chart')
plt.xlabel('x')
plt.ylabel('y')

plt.show()

python tutorial on using matplotlib to draw a line chart

##2. Legend

Specify label when plotting, and then call the legend method to draw the legend. For example:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 100)
y1, y2 = np.sin(x), np.cos(x)

plt.plot(x, y1, label='y = sin(x)')
plt.plot(x, y2, label='y = cos(x)')
plt.legend()
plt.show()

python tutorial on using matplotlib to draw a line chart

legend method accepts a loc keyword parameter to set the position of the legend. The value is a number or a string:

0: 'best'


1: 'upper right'


2: 'upper left'


3: 'lower left'


4: 'lower right'


5: 'right'


6: 'center left'


7: 'center right'


8: 'lower center'


9: ' upper center'


10: 'center'


3. Line style

(1) Color

The keyword parameter color (or c) of the plot method is used to set the color of the line. Possible values ​​are:

1, color name or abbreviation


b: blue


g: green


r: red


c: cyan


m: magenta


y: yellow


k: black


w: white


2、#rrggbb


3、(r, g, b) or (r, g, b, a), where r g b a takes the string form of floating point numbers between [0, 1]


4 and [0, 1], representing grayscale values. 0 means black, 1 means white


(2) Style

The keyword parameter linestyle (or ls) of the plot method is used to set the line style. Possible values ​​are:

  • -, solid

  • --, dashed

  • -. , dashdot

  • :, ​​dotted

  • '', ' ', None

  • ##(3 )Thickness

Set the keyword parameter linewidth (or lw) of the plot method to change the thickness of the line, and its value is a floating point number.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 100)
y1, y2 = np.sin(x), np.cos(x)

plt.plot(x, y1, c='r', ls='--', lw=3)
plt.plot(x, y2, c='#526922', ls='-.')
plt.show()

python tutorial on using matplotlib to draw a line chart
##4. marker

The following keyword parameters Can be used to set the marker style:

marker
  • markeredgecolor or mec
  • markeredgewidth or mew
  • ##markerfacecolor or mfc

  • markerfacecoloralt or mfcalt

  • markersize or ms

  • The possible values ​​of marker are:

'.': point marker

  • ',': pixel marker

  • 'o': circle marker

  • 'v': triangle_down marker

  • ##' ^': triangle_up marker

  • '
  • '>': triangle_right marker

  • '1': tri_down marker

  • '2': tri_up marker

  • '3': tri_left marker

  • '4': tri_right marker

  • 's': square marker

  • 'p': pentagon marker

  • '*': star marker

  • 'h': hexagon1 marker

  • 'H': hexagon2 marker

  • '+': plus marker

  • 'x': x marker

  • 'D': diamond marker

  • 'd': thin_diamond marker

  • '|': vline marker

  • '_': hline marker

例如:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 10)
y1, y2 = np.sin(x), np.cos(x)

plt.plot(x, y1, marker='o', mec='r', mfc='w')
plt.plot(x, y2, marker='*', ms=10)
plt.show()

python tutorial on using matplotlib to draw a line chart

另外,marker关键字参数可以和color以及linestyle这两个关键字参数合并为一个字符串。例如:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 10)
y1, y2 = np.sin(x), np.cos(x)

plt.plot(x, y1, 'ro-')
plt.plot(x, y2, 'g*:', ms=10)
plt.show()

python tutorial on using matplotlib to draw a line chart

更多python tutorial on using matplotlib to draw a line chart相关文章请关注PHP中文网!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What data types can be stored in a Python array?What data types can be stored in a Python array?Apr 27, 2025 am 12:11 AM

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

What happens if you try to store a value of the wrong data type in a Python array?What happens if you try to store a value of the wrong data type in a Python array?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Which is part of the Python standard library: lists or arrays?Which is part of the Python standard library: lists or arrays?Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

What should you check if the script executes with the wrong Python version?What should you check if the script executes with the wrong Python version?Apr 27, 2025 am 12:01 AM

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

What are some common operations that can be performed on Python arrays?What are some common operations that can be performed on Python arrays?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

In what types of applications are NumPy arrays commonly used?In what types of applications are NumPy arrays commonly used?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

When would you choose to use an array over a list in Python?When would you choose to use an array over a list in Python?Apr 26, 2025 am 12:12 AM

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

Are all list operations supported by arrays, and vice versa? Why or why not?Are all list operations supported by arrays, and vice versa? Why or why not?Apr 26, 2025 am 12:05 AM

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software