Sunday, December 29, 2019

How to Create a Chart

Before you begin, import pyplot to your programming environment and set the name as plt as shown below:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])


When you enter this code, you will have created a Line2D object. An object in this case is a linear representation of the trends you will plot within a given chart. To view the plot, you will use the function below:

plt.show()

The result should be a plotting window similar to the one below:



Depending on the platform you are using, in some cases your chart will display without necessarily calling the show() function, especially if you are using iPython QtConsole. Once this plot is prepared you must provide a definition for the two arrays on the x and y axis. The blue line in the example above represents all the points in your plot. This is the default configuration when your data does not have a legend, axis labels, or a title.

Beyond using pyplot commands for single figures, you can work with lots of figures at the same time in Matplotlib. You can take things further and introduce new plots within each figure. Other than using multiple subplots, you can also use the subplot() function to create multiple drawing areas in the main figure.

The subplot() function also helps you choose the subplot to focus your work on. Once selected, any commands passed will be called on the current subplot. A careful look at the subplot() function reveals three integers, each of which serves a unique role.

The first integer outlines the number of vertical divisions available in the figure. The second integer outlines the number of horizontal divisions available in the figure. The third integer outlines the subplot where your commands are directed.

t = np.arange(0,5,0.1)
y1 = np.sin(2*np.pi*t)
y2 = np.sin(2*np.pi*t)
plt.subplot(211)
plt.plot(t,y1,'b-.')
plt.subplot(212)
plt.plot(t,y2,'r--')

You should have the following plot:



In the next example, we will create vertical divisions from the plots above using the code below:

t = np.arange(0.,1.,0.05)
y1 = np.sin(2*np.pi*t)
y2 = np.cos(2*np.pi*t)

plt.subplot(121)
plt.plot(t,y1,'b-.')
plt.subplot(122)
plt.plot(t,y2,'r--')
plt.show()

You should have the plot below:





Share:

0 comments:

Post a Comment