Explain Plotting Using pandas DataFrames Displaying Figures and Saving Figures in Matplotlib

9 a] Explain Plotting Using pandas DataFrames Displaying Figures and Saving Figures in Matplotlib

With plt.plot([x], y, [fmt]), you can plot data points as lines and/or markers. The function returns a list of Line2D objects representing the plotted data. By default, if you do not provide a format string (fmt), the data points will be connected with straight, solid lines. plt.plot([0, 1, 2, 3], [2, 4, 6, 8]) produces a plot, as shown in the following diagram. Since x is optional and the default values are [0, …, N-1], plt.plot([2, 4, 6, 8]) results in the same plot:

plotting data points as a line

If you want to plot markers instead of lines, you can just specify a format string with any marker type. For example, plt.plot([0, 1, 2, 3], [2, 4, 6, 8], 'o') displays data points as circles, as shown in the following diagram:

plotting data points with marker

Plotting Using pandas DataFrames
It is pretty straightforward to use pandas.DataFrame as a data source. Instead of providing x and y values, you can provide the pandas.DataFrame in the data parameter and give keys for x and y, as follows:

plt.plot('x_key', 'y_key', data=df)

Displaying Figures
plt.show() is used to display a Figure or multiple Figures. To display Figures within a Jupyter Notebook, simply set the %matplotlib inline command at the beginning of the code.
If you forget to use plt.show(), the plot won’t show up. We will learn how to save the Figure in the next section.
Saving Figures
The plt.savefig(fname) saves the current Figure. There are some useful optional parameters you can specify, such as dpi, format, or transparent. The following code snippet gives an example of how you can save a Figure:

plt.figure()
plt.plot([1, 2, 4, 5], [1, 3, 4, 3], '-o')
plt.savefig('lineplot.png', dpi=300, bbox_inches='tight')
#bbox_inches='tight' removes the outer white margins
line chart

Leave a Reply

Your email address will not be published. Required fields are marked *