Plotting in Python | Set 1

Arrays | Counters | NumPy | Python Methods and Functions

Install

The easiest way to install matplotlib — this is to use pip. Enter the following command in terminal:

 pip install matplotlib 

OR you can download it from here and install manually.

Getting started (laying the line)

# import the required module

import matplotlib.pyplot as plt

 
# x-axis values ​​

x = [ 1 , 2 , 3 ]

# corresponding Y-axis values ​​

y = [ 2 , 4 , 1 ]

 
# plotting dots
plt.plot (x, y)

 
# x-axis title

plt.xlabel ( `x - axis` )

# axis name Y

plt.ylabel ( `y - axis` )

  
# giving a title to my graphic

plt.title ( `My first graph!` )

 
# plot display function
plt.show ()

Output:

The code seems self-evident. The following steps were taken:

  • Define the X-axis and corresponding Y-axis values ​​as lists.
  • Place them on the canvas using the .plot () function .
  • Name the X and Y axes using the .xlabel () and .ylabel () functions.
  • Name your graphic, using the .title () function .
  • Finally, we use .show () function .

Draw two or more lines on the same site

import matplotlib.pyplot as plt

  
# line 1 point

x1 = [ 1 , 2 , 3 ]

y1 = [ 2 , 4 , 1 ]

# line drawing 1 point

plt.plot (x1, y1, label = "line 1" )

 
# line 2 points

x2 = [ 1 , 2 , 3 ]

y2 = [ 4 , 1 , 3 ]

# line 2 points

plt.plot (x2, y2, label = "line 2" )

 
# x-axis title

plt.xlabel ( `x - axis` )

# Y axis name

plt.ylabel ( `y - axis` )

# giving a title to my graphic

plt.title ( ` Two lines on same graph! ` )

 
# show story legend
plt.legend ()

 
# plot display function
plt.show ()

Output:

  • Here we are plotting two lines on one graph. We distinguish them by giving them a name ( label ), which is passed as an argument to the .plot () function.
  • The small rectangle with information about the line type and its color is called a legend. We can add a legend to our graphics using the .legend () function .

C ustomization from parcels

Here we discuss some basic settings that apply to almost any plot.

import matplotlib.pyplot as plt

 
# x-axis values ​​

x = [ 1 , 2 , 3 , 4 , 5 , 6 ]

# corresponding Y-axis values ​​

y = [ 2 , 4 , 1 , 5 , 2 , 6 ]

 
# dots

plt.plot (x, y, color = `green` , linestyle = ` dashed` , linewidth = 3 ,

marker = `o` , markerfacecolor = ` blue ` , markersize = 12 )

  
# set the x and y axis range

plt.ylim ( 1 , 8 )

plt.xlim ( 1 , 8 )

 
# x-axis title

plt.xlabel ( `x - axis` )

# Y-axis name

plt .ylabel ( `y - axis` )

  
# giving a title to my graphic

plt.title ( `Some cool customizations!` )

 
# plot show function
plt.show ()

Output:

As you can see, we have made several settings such as

  • setting line width, line style, line color.
  • mar setting ker, marker face color, marker size.
  • override the X and Y axis range. If not overridden, the pyplot module uses autoscale to set the range and scale of the axis.

Histogram

import matplotlib.pyplot as plt

 
# x-coordinates of the left side of the bars

left = [ 1 , 2 , 3 , 4 , 5 ]

 
# bar heights

height = [ 10 , 24 , 36 , 40 , 5 ]

 
# bar labels

tick_label = [ `one` , ` two ` , ` three` , `four` , ` five` ]

 
# building a histogram

plt.bar (left, height, tick_label = tick_label,

  width = 0.8 , color = [ ` red` , `green` ])

 
# axis name X

plt.xlabel ( `x - axis` )

# Y-axis name

plt.ylabel ( `y - axis` )

# story title

plt.title ( `My bar chart!` )

 
# plot show function
plt.show ()

Output:

  • Here we use the plt.bar () function to plot the bar graph.
  • The X-coordinates of the left side of the bars are passed along with the height of the bars.
  • You can also name the X-axis coordinates by defining tick_labels

Histogram

import matplotlib.pyplot as plt

 
# frequencies

ages = [ 2 , 5 , 70 , 40 , 30 , 45 , 50 , 45 , 43 , 40 , 44 ,

60 , 7 , 13 , 57 , 18 , 90 , 77 , 32 , 21 , 20 , 40 ]

 
# setting ranges and no. ranges

range = ( 0 , 100 )

bins = 10  

 
# building a histogram

plt.hist (ages, bins, range , color = `green` ,

  histtype = `bar` , rwidth = 0.8 )

 
X-axis label

plt.xlabel ( `age` )

# frequency tag

plt.ylabel ( `No. of people` )

# story name

plt.title ( `My histogram` )

 
# plot show function
plt.show ( )

Output:

  • Here we use the plt.hist () function to plot the histogram.
  • frequencies are transmitted as a list of ages .
  • The range can be set by specifying a tuple containing the minimum and maximum values.
  • The next step is “ selection "range of values, that is, section Dividing the entire range of values ​​into a number of bins, and then counting the number of values ​​that fall within each bin. Here we have defined bins = 10. So there are 100/10 = 10 bins.

Dot plot

Output:

  • Here we use the plt.scatter () function to plot the scatter plot.
  • Similar to the line, we also define the x and the corresponding y-axis values.
  • The marker argument is used to set the character to use as a marker. Its size can be determined using the s parameter.

Pie Chart

import matplotlib.pyplot as plt

 
# X-axis values

x = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]

# Y-axis values ​​

y = [ 2 , 4 , 5 , 7 , 6 , 8 , 9 , 11 , 12 , 12 ]

 
# plotting points as a scatter plot

plt.scatter (x, y, label = " stars " , color = "green"

marker = "*" , s = 30 )

 
X-axis label

plt.xlabel ( `x - axis` )

# frequency tag

plt.ylabel ( ` y - axis` )

# plot title

plt.title ( `My scatter plot!` )

# shows the legend
plt.legend ()

 
# plot show function
plt.show ()

import matplotlib.pyplot as plt

  
#define tags

activities = [ ` eat` , `sleep` , ` work` , `play` ]

  
# the part covered by each label

slices = [ 3 , 7 , 8 , 6 ]

 
# color for each tag

colors = [ `r` , ` y ` , ` g` , `b` ]

  
# building a pie chart

plt.pie (slices, labels = activities, colors = colors, 

startangle = 90 , shadow = True , explode = ( 0 , 0 , 0.1 , 0 ),

radius = 1.2 , autopct = `% 1.1f %%` )

 
# sketching the legend
plt.legend ()

  
# show plot
plt.show ()

The output of the above program looks like this:

  • Here we are build a pie chart using the plt.pie () method .
  • First of all, we define labels using a list called actions .
  • Then a portion of each label can be defined using another list called slices .
  • The color for each label is defined with using a list called colors .
  • shadow = True will show the shadow by e each label on the pie chart.
  • startangle rotates the start of the pie chart the specified degrees counterclockwise from the x-axis.
  • explode is used to set the fraction of the radius with which we offset each wedge.
  • autopct is used to format the value of each label. Here we have set it to only show a percentage up to 1 decimal place.

Plot the curves of this equation

# import required modules

import matplotlib.pyplot as plt

import numpy as np

 
# setting x coordinates

x = np.arange ( 0 , 2 * (np.pi), 0.1 )

# setting the appropriate y - coordinates

y = np.sin (x)

 
# fill points
plt.plot (x, y)

                                                                                                                                                 
# plot show function
plt.show ()

The output of the above program looks like this:

Here we use NumPy, which is a generic package for handling arrays in Python.

  • To set the x-axis values, we we use the np.arange () method, in which the first two arguments are for a range, and the third is — for incremental increments. The result is a NumPy array.
  • To get the corresponding Y-axis values, we simply use the predefined np.sin () method on the numpy array.
  • Finally, we plot the points by passing the x and y arrays to the plt.plot () function .

So, in this part, we discussed the different types of plots that we can create in matplotlib. There are a few more plots that were not covered, but the most significant ones are discussed here —

Get Solution for free from DataCamp guru