Informatics Practices · Ch 4 — Plotting Data using Matplotlib
The Pandas Plot Function (Pandas Visualisation)
The Pandas Plot Function (Pandas Visualisation)
The plot() method built into Pandas Series and DataFrame objects is a convenient shortcut. Before Pandas version 0.17.0, you had to import matplotlib.pyplot and call plt.plot() directly. Now, any Series or DataFrame object (say s or df) can call its own .plot() method. This method is a simple wrapper around the pyplot plot() function — it does the same thing but with less typing.
If you have a DataFrame named df, you can write df.plot() instead of plt.plot(df). You can still use all the usual matplotlib.pyplot functions alongside it, like plt.ylabel(), plt.title(), and plt.show(). For example, to set a chart title after calling df.plot(), you would write plt.title('Average weight with respect to average height').
The real power of the Pandas .plot() method is the kind keyword argument. By passing a string to kind, you instantly change the entire chart type. The general syntax is:
df.plot(kind='type')
where 'type' is one of the strings listed below.
kind= value | Plot type |
|---|---|
'line' | Line plot (this is the default) |
'bar' | Vertical bar chart |
'barh' | Horizontal bar chart |
'hist' | Histogram |
'box' | Box plot |
'area' | Area plot |
'pie' | Pie chart |
'scatter' | Scatter plot |
You can also combine Pandas .plot() with pyplot customisation. For instance, you can set marker style, marker size, line colour, line width, and line style just as you would with plt.plot(). A typical call might look like:
df.plot(kind='line', marker='*', markersize=10, color='green', linewidth=2, linestyle='dashdot')
plt.ylabel('Height in cm')
plt.title('Average weight with respect to average height')
plt.show()
``` …
| kind = | Plot type |
|---|---|
| line | Line plot (default) |
| bar | Vertical bar plot |
| barh | Horizontal bar plot |
| hist | Histogram |
| box | Boxplot |
| area | Area plot |