Movatterモバイル変換


[0]ホーム

URL:


Menu
×
Sign In
+1 Get Certified For Teachers Spaces Plus Get Certified For Teachers Spaces Plus
   ❮     
     ❯   

Python Tutorial

Python HOMEPython IntroPython Get StartedPython SyntaxPython CommentsPython VariablesPython Data TypesPython NumbersPython CastingPython StringsPython BooleansPython OperatorsPython ListsPython TuplesPython SetsPython DictionariesPython If...ElsePython MatchPython While LoopsPython For LoopsPython FunctionsPython LambdaPython ArraysPython OOPPython Classes/ObjectsPython InheritancePython IteratorsPython PolymorphismPython ScopePython ModulesPython DatesPython MathPython JSONPython RegExPython PIPPython Try...ExceptPython String FormattingPython User InputPython VirtualEnv

File Handling

Python File HandlingPython Read FilesPython Write/Create FilesPython Delete Files

Python Modules

NumPy TutorialPandas TutorialSciPy TutorialDjango Tutorial

Python Matplotlib

Matplotlib IntroMatplotlib Get StartedMatplotlib PyplotMatplotlib PlottingMatplotlib MarkersMatplotlib LineMatplotlib LabelsMatplotlib GridMatplotlib SubplotMatplotlib ScatterMatplotlib BarsMatplotlib HistogramsMatplotlib Pie Charts

Machine Learning

Getting StartedMean Median ModeStandard DeviationPercentileData DistributionNormal Data DistributionScatter PlotLinear RegressionPolynomial RegressionMultiple RegressionScaleTrain/TestDecision TreeConfusion MatrixHierarchical ClusteringLogistic RegressionGrid SearchCategorical DataK-meansBootstrap AggregationCross ValidationAUC - ROC CurveK-nearest neighbors

Python DSA

Python DSALists and ArraysStacksQueuesLinked ListsHash TablesTreesBinary TreesBinary Search TreesAVL TreesGraphsLinear SearchBinary SearchBubble SortSelection SortInsertion SortQuick SortCounting SortRadix SortMerge Sort

Python MySQL

MySQL Get StartedMySQL Create DatabaseMySQL Create TableMySQL InsertMySQL SelectMySQL WhereMySQL Order ByMySQL DeleteMySQL Drop TableMySQL UpdateMySQL LimitMySQL Join

Python MongoDB

MongoDB Get StartedMongoDB Create DBMongoDB CollectionMongoDB InsertMongoDB FindMongoDB QueryMongoDB SortMongoDB DeleteMongoDB Drop CollectionMongoDB UpdateMongoDB Limit

Python Reference

Python OverviewPython Built-in FunctionsPython String MethodsPython List MethodsPython Dictionary MethodsPython Tuple MethodsPython Set MethodsPython File MethodsPython KeywordsPython ExceptionsPython Glossary

Module Reference

Random ModuleRequests ModuleStatistics ModuleMath ModulecMath Module

Python How To

Remove List DuplicatesReverse a StringAdd Two Numbers

Python Examples

Python ExamplesPython CompilerPython ExercisesPython QuizPython ServerPython SyllabusPython Study PlanPython Interview Q&APython BootcampPython CertificatePython Training

MatplotlibScatter


Creating Scatter Plots

With Pyplot, you can use thescatter() function to draw a scatter plot.

Thescatter() function plots one dot for each observation. It needs two arrays of the same length, one for the values of the x-axis, and one for values on the y-axis:

Example

A simple scatter plot:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])

plt.scatter(x, y)
plt.show()

Result:

Try it Yourself »

The observation in the example above is the result of 13 cars passing by.

The X-axis shows how old the car is.

The Y-axis shows the speed of the car when it passes.

Are there any relationships between the observations?

It seems that the newer the car, the faster it drives, but that could be a coincidence, after all we only registered 13 cars.


Compare Plots

In the example above, there seems to be a relationship between speed and age,but what if we plot the observations from another day as well?Will the scatter plot tell us something else?

Example

Draw two plots on the same figure:

import matplotlib.pyplot as plt
import numpy as np

#day one, the age and speed of 13 cars:
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)

#day two, the age and speed of 15 cars:
x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
y = np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
plt.scatter(x, y)

plt.show()

Result:

Try it Yourself »

Note: The two plots are plotted with two different colors, by default blue and orange, you will learn how to change colors later in this chapter.

By comparing the two plots, I think it is safe to say that they both gives us the same conclusion: the newer the car, the faster it drives.



Colors

You can set your own color for each scatter plot with thecolor or thec argument:

Example

Set your own color of the markers:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y, color = 'hotpink')

x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
y = np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
plt.scatter(x, y, color = '#88c999')

plt.show()

Result:

Try it Yourself »

Color Each Dot

You can even set a specific color for each dot by using an array of colors as value for thec argument:

Note: Youcannot use thecolor argument for this, only thec argument.

Example

Set your own color of the markers:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
colors = np.array(["red","green","blue","yellow","pink","black","orange","purple","beige","brown","gray","cyan","magenta"])

plt.scatter(x, y, c=colors)

plt.show()

Result:

Try it Yourself »

ColorMap

The Matplotlib module has a number of available colormaps.

A colormap is like a list of colors, where each color has a value that ranges from 0 to 100.

Here is an example of a colormap:

This colormap is called 'viridis' and as you can see it ranges from 0, which is a purple color, up to 100, which is a yellow color.

How to Use the ColorMap

You can specify the colormap with the keyword argumentcmap with the value of the colormap, in this case'viridis' which is one of the built-in colormaps available in Matplotlib.

In addition you have to create an array with values (from 0 to 100), one value for each point in the scatter plot:

Example

Create a color array, and specify a colormap in the scatter plot:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])

plt.scatter(x, y, c=colors, cmap='viridis')

plt.show()

Result:

Try it Yourself »

You can include the colormap in the drawing by including theplt.colorbar() statement:

Example

Include the actual colormap:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])

plt.scatter(x, y, c=colors, cmap='viridis')

plt.colorbar()

plt.show()

Result:

Try it Yourself »

Available ColorMaps

You can choose any of the built-in colormaps:

Name Reverse
AccentTry it » Accent_rTry it »
BluesTry it » Blues_rTry it »
BrBGTry it » BrBG_rTry it »
BuGnTry it » BuGn_rTry it »
BuPuTry it » BuPu_rTry it »
CMRmapTry it » CMRmap_rTry it »
Dark2Try it » Dark2_rTry it »
GnBuTry it » GnBu_rTry it »
GreensTry it » Greens_rTry it »
GreysTry it » Greys_rTry it »
OrRdTry it » OrRd_rTry it »
OrangesTry it » Oranges_rTry it »
PRGnTry it » PRGn_rTry it »
PairedTry it » Paired_rTry it »
Pastel1Try it » Pastel1_rTry it »
Pastel2Try it » Pastel2_rTry it »
PiYGTry it » PiYG_rTry it »
PuBuTry it » PuBu_rTry it »
PuBuGnTry it » PuBuGn_rTry it »
PuOrTry it » PuOr_rTry it »
PuRdTry it » PuRd_rTry it »
PurplesTry it » Purples_rTry it »
RdBuTry it » RdBu_rTry it »
RdGyTry it » RdGy_rTry it »
RdPuTry it » RdPu_rTry it »
RdYlBuTry it » RdYlBu_rTry it »
RdYlGnTry it » RdYlGn_rTry it »
RedsTry it » Reds_rTry it »
Set1Try it » Set1_rTry it »
Set2Try it » Set2_rTry it »
Set3Try it » Set3_rTry it »
SpectralTry it » Spectral_rTry it »
WistiaTry it » Wistia_rTry it »
YlGnTry it » YlGn_rTry it »
YlGnBuTry it » YlGnBu_rTry it »
YlOrBrTry it » YlOrBr_rTry it »
YlOrRdTry it » YlOrRd_rTry it »
afmhotTry it » afmhot_rTry it »
autumnTry it » autumn_rTry it »
binaryTry it » binary_rTry it »
boneTry it » bone_rTry it »
brgTry it » brg_rTry it »
bwrTry it » bwr_rTry it »
cividisTry it » cividis_rTry it »
coolTry it » cool_rTry it »
coolwarmTry it » coolwarm_rTry it »
copperTry it » copper_rTry it »
cubehelixTry it » cubehelix_rTry it »
flagTry it » flag_rTry it »
gist_earthTry it » gist_earth_rTry it »
gist_grayTry it » gist_gray_rTry it »
gist_heatTry it » gist_heat_rTry it »
gist_ncarTry it » gist_ncar_rTry it »
gist_rainbowTry it » gist_rainbow_rTry it »
gist_sternTry it » gist_stern_rTry it »
gist_yargTry it » gist_yarg_rTry it »
gnuplotTry it » gnuplot_rTry it »
gnuplot2Try it » gnuplot2_rTry it »
grayTry it » gray_rTry it »
hotTry it » hot_rTry it »
hsvTry it » hsv_rTry it »
infernoTry it » inferno_rTry it »
jetTry it » jet_rTry it »
magmaTry it » magma_rTry it »
nipy_spectralTry it » nipy_spectral_rTry it »
oceanTry it » ocean_rTry it »
pinkTry it » pink_rTry it »
plasmaTry it » plasma_rTry it »
prismTry it » prism_rTry it »
rainbowTry it » rainbow_rTry it »
seismicTry it » seismic_rTry it »
springTry it » spring_rTry it »
summerTry it » summer_rTry it »
tab10Try it » tab10_rTry it »
tab20Try it » tab20_rTry it »
tab20bTry it » tab20b_rTry it »
tab20cTry it » tab20c_rTry it »
terrainTry it » terrain_rTry it »
twilightTry it » twilight_rTry it »
twilight_shiftedTry it » twilight_shifted_rTry it »
viridisTry it » viridis_rTry it »
winterTry it » winter_rTry it »

Size

You can change the size of the dots with thes argument.

Just like colors, make sure the array for sizes has the same length as the arrays for the x- and y-axis:

Example

Set your own size for the markers:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
sizes = np.array([20,50,100,200,500,1000,60,90,10,300,600,800,75])

plt.scatter(x, y, s=sizes)

plt.show()

Result:

Try it Yourself »

Alpha

You can adjust the transparency of the dots with thealpha argument.

Just like colors, make sure the array for sizes has the same length as the arrays for the x- and y-axis:

Example

Set your own size for the markers:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
sizes = np.array([20,50,100,200,500,1000,60,90,10,300,600,800,75])

plt.scatter(x, y, s=sizes, alpha=0.5)

plt.show()

Result:

Try it Yourself »

Combine Color Size and Alpha

You can combine a colormap with different sizes of the dots. This is best visualized if the dots are transparent:

Example

Create random arrays with 100 values for x-points, y-points, colors and sizes:

import matplotlib.pyplot as plt
import numpy as np

x = np.random.randint(100, size=(100))
y = np.random.randint(100, size=(100))
colors = np.random.randint(100, size=(100))
sizes = 10 * np.random.randint(100, size=(100))

plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='nipy_spectral')

plt.colorbar()

plt.show()

Result:

Try it Yourself »

 
Track your progress - it's free!
 

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp