[Go to site: main page, start]

0% found this document useful (0 votes)
18 views23 pages

Visualizing Data with Matplotlib

Matplotlib is a versatile Python library for data visualization that supports various types of plots such as histograms, scatter plots, and bar charts, making it a popular alternative to MATLAB. The document provides examples of how to use Matplotlib for different types of data analysis, including bivariate and univariate analyses, as well as customization options for plots. It also covers advanced features like subplots and 3D plotting.

Uploaded by

Harsimar Kaur
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views23 pages

Visualizing Data with Matplotlib

Matplotlib is a versatile Python library for data visualization that supports various types of plots such as histograms, scatter plots, and bar charts, making it a popular alternative to MATLAB. The document provides examples of how to use Matplotlib for different types of data analysis, including bivariate and univariate analyses, as well as customization options for plots. It also covers advanced features like subplots and 3D plotting.

Uploaded by

Harsimar Kaur
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Matplotlib in Python

What is Matplotlib in Python?


Matplotlib is a cross-platform, data visualization and graphical plotting library
(histograms, scatter plots, bar charts, etc) for Python and its numerical extension
NumPy. As such, it offers a viable open source alternative to MATLAB. Developers can
also use matplotlib’s APIs (Application Programming Interfaces) to embed plots in GUI
applications.

Matplotlib styles list


Types of Data

Numerical Data
Categorical Data

In [ ]: import numpy as np
import pandas as pd
import [Link] as plt
import seaborn as sns
[Link]('fivethirtyeight')

In [ ]: df = sns.load_dataset('tips')

In [ ]: [Link]()

Out[ ]: total_bill tip sex smoker day time size

0 16.99 1.01 Female No Sun Dinner 2

1 10.34 1.66 Male No Sun Dinner 3

2 21.01 3.50 Male No Sun Dinner 3

3 23.68 3.31 Male No Sun Dinner 2

4 24.59 3.61 Female No Sun Dinner 4


2D Line
Bivariate Analysis
Categorical -> Numerical and Numerical -> Numerical
Use case - Time series data

In [ ]: df1 = [Link](5)

In [ ]: [Link](df1['total_bill'], df1['tip'])
[Link]()

In [ ]: # title and label


[Link](df1['total_bill'], df1['tip'])
[Link]('Graph')
[Link]('total bill')
[Link]('tip')
[Link]()

In [ ]: # multi plot in same graph


[Link](df1['total_bill'], df1['tip'], color='green')
[Link](df1['total_bill'], df1['size'])
[Link]('Graph')
[Link]('total bill')
[Link]('tip')
[Link]()

In [ ]: # line style
[Link](df1['total_bill'], df1['tip'], color='green', linestyle='dotted'
[Link](df1['total_bill'], df1['size'], linestyle='dashed')
[Link]('Graph')
[Link]('total bill')
[Link]('tip')
[Link]()

In [ ]: df = sns.load_dataset('iris')
[Link]()
df1 = [Link](5)

In [ ]: [Link](df1['sepal_length'], df1['sepal_width'],
color='green', linestyle='dashdot')
[Link]('Graph')
[Link]('total bill')
[Link]('tip')
[Link]()
In [ ]: [Link](df1['sepal_length'], df1['sepal_width'],
color='green', linestyle='dashdot', linewidth=3, marker='o')
[Link]('Graph')
[Link]('total bill')
[Link]('tip')
[Link]()

In [ ]: # label
df = sns.load_dataset('tips')
df1 = [Link](5)

[Link](df1['total_bill'], df1['tip'], color='green',


linestyle='dotted', label='tip')
[Link](df1['total_bill'], df1['size'], linestyle='dashed', label='size'
[Link]('Graph')
[Link]('total bill')
[Link]('tip')
[Link](loc='upper right')
[Link]()
In [ ]: # limiting axes
price = [48000, 54000, 57000, 48000, 47000, 45000, 450000]
year = [2015, 2016, 2017, 2018, 2019, 2020, 2021]

[Link](year, price)
[Link](0, 100000)
[Link]()

Scatter
Bivariate Analysis
numerical vs numerical
Use case - finding correlation

In [ ]: df = sns.load_dataset('iris')
[Link]()
df1 = [Link](5)
df1

Out[ ]: sepal_length sepal_width petal_length petal_width species

0 5.1 3.5 1.4 0.2 setosa

1 4.9 3.0 1.4 0.2 setosa


2 4.7 3.2 1.3 0.2 setosa

3 4.6 3.1 1.5 0.2 setosa

4 5.0 3.6 1.4 0.2 setosa

In [ ]: [Link](df['sepal_length'], df['sepal_width'])
[Link]()

In [ ]: # color change and marker


[Link](df['sepal_length'], df['sepal_width'], color='orange', marker
[Link]()

In [ ]: # size
[Link](df['sepal_length'], df['sepal_width'],
color='orange', marker='o', s=df['petal_width']*40)
[Link]()
In [ ]: [Link](df['sepal_length'], df['sepal_width'], 'o')
[Link]()

**Bar Chart**
Bivariate Analysis
Numerical vs Categorical
Use case - Aggregate analysis of groups

In [ ]: [Link](df['species'], df['sepal_length'],
width=0.5, color=['orange'])
[Link]()
In [ ]: [Link](df['species'], df['sepal_length'])
[Link]()

In [ ]: # stacked bar chart


[Link](df['species'], df['sepal_length'])
[Link](df['species'], df['sepal_width'], bottom=df['sepal_length'])
[Link](df['species'], df['petal_length'],
bottom=df['sepal_length'] + df['sepal_width'])
[Link]()
**Histogram**
Univariate Analysis
Numerical col
Use case - Frequency Count

In [ ]: [Link]()

Out[ ]: sepal_length sepal_width petal_length petal_width

count 150.000000 150.000000 150.000000 150.000000

mean 5.843333 3.057333 3.758000 1.199333

std 0.828066 0.435866 1.765298 0.762238

min 4.300000 2.000000 1.000000 0.100000

25% 5.100000 2.800000 1.600000 0.300000

50% 5.800000 3.000000 4.350000 1.300000

75% 6.400000 3.300000 5.100000 1.800000

max 7.900000 4.400000 6.900000 2.500000

In [ ]: [Link](df['sepal_length'])
[Link]()

In [ ]: # using bin
[Link](df['sepal_length'], bins=[1, 4.5,
7, 8], edgecolor='r', log=True)
[Link]()
**Pie chart**
Univariate/ Bivariate Analysis
Categorical vs Numerical
Use case - To find contribution on a standard scale

In [ ]: data = [23, 45, 100, 20, 49]


subjects = ['eng', 'science', 'maths', 'sst', 'hindi']
[Link](data, labels=subjects, autopct="%0.1f%%")
[Link]()

In [ ]: [Link](data, labels=subjects, autopct="%0.1f%%",


explode=[0.2, 0, 0.1, 0, 0], labeldistance=1.1)
[Link]()
In [ ]: [Link](data, labels=subjects, autopct="%0.1f%%", textprops={'fontsize':
[Link]()

In [ ]: [Link](data, labels=subjects, autopct="%0.1f%%", radius=1.3)


[Link]()

In [ ]: [Link](data, labels=subjects, autopct="%0.1f%%", counterclock=False)


[Link]()
In [ ]: [Link]('ggplot')

In [ ]: [Link](data, labels=subjects, autopct="%0.1f%%")


[Link]()

In [ ]: [Link](df['sepal_length'], df['sepal_width'], 'o')


[Link]()

In [ ]: price = [48000, 54000, 57000, 48000, 47000, 45000, 450000]


year = [2015, 2016, 2017, 2018, 2019, 2020, 2021]

[Link](year, price)
[Link](0, 100000)
[Link]()

In [ ]: [Link](df['sepal_length'], df['sepal_width'])
[Link]()

In [ ]: df['species'].unique()
array(['setosa', 'versicolor', 'virginica'], dtype=object)
Out[ ]:

In [ ]: df['species'] = df['species'].replace(
{'setosa': 0, 'versicolor': 1, 'virginica': 2})

In [ ]: [Link]()

Out[ ]: sepal_length sepal_width petal_length petal_width species

145 6.7 3.0 5.2 2.3 2

146 6.3 2.5 5.0 1.9 2

147 6.5 3.0 5.2 2.0 2

148 6.2 3.4 5.4 2.3 2

149 5.9 3.0 5.1 1.8 2

In [ ]: [Link](df['sepal_length'], df['petal_length'], c=df['species'])


[Link]()

In [ ]: # color
[Link](df['sepal_length'], df['petal_length'],
c=df['species'], cmap='winter')
[Link]()
[Link]()

C:\Users\dhanr\AppData\Local\Temp\ipykernel_23404\[Link]: Matplo
tlibDeprecationWarning: Auto-removal of grids by pcolor() and pcolormesh
() is deprecated since 3.5 and will be removed two minor releases later;
please call grid(False) first.
[Link]()

In [ ]: # size
[Link](figsize=(10, 6))
[Link](df['sepal_length'], df['petal_length'],
c=df['species'], cmap='winter')
[Link]('Sepal Length')
[Link]('petal length')
[Link]()
[Link]()

C:\Users\dhanr\AppData\Local\Temp\ipykernel_23404\[Link]: Matplo
tlibDeprecationWarning: Auto-removal of grids by pcolor() and pcolormesh
() is deprecated since 3.5 and will be removed two minor releases later;
please call grid(False) first.
[Link]()
**Annotations**
In [ ]: x = [1, 2, 3, 4]
y = [5, 6, 7, 8]

[Link](x, y)
[Link](1, 5, 'Point 1')
[Link](2, 6, 'Point 2')
[Link](3, 7, 'Point 3')
[Link](4, 8, 'Point 4')

Text(4, 8, 'Point 4')


Out[ ]:

In [ ]: [Link](figsize=(10, 6))
[Link](df['sepal_length'], df['petal_length'],
c=df['species'], cmap='winter')
[Link]('Sepal Length')
[Link]('petal length')
[Link](6.2, color='r')
[Link](3.5, color='blue')
[Link]()
[Link]()

C:\Users\dhanr\AppData\Local\Temp\ipykernel_23404\[Link]: Matplo
tlibDeprecationWarning: Auto-removal of grids by pcolor() and pcolormesh
() is deprecated since 3.5 and will be removed two minor releases later;
please call grid(False) first.
[Link]()

**Subplot**
In [ ]: fig, ax = [Link](ncols=1, nrows=2, sharex=True, figsize=(10, 6))
ax[0].scatter(df['sepal_length'], df['petal_length'])
ax[0].set_xlabel('Sepal lenght')

ax[1].scatter(df['sepal_width'], df['petal_width'], color='blue')


ax[1].set_xlabel('Sepal width')
[Link]()
In [ ]: [Link]('fivethirtyeight')

In [ ]: fig, ax = [Link](ncols=2, nrows=2, sharex=False, figsize=(15, 10))


ax[0, 0].scatter(df['sepal_length'], df['petal_length'])
ax[0, 0].set_xlabel('Sepal lenght')

ax[0, 1].scatter(df['sepal_length'], df['sepal_width'], color='green')


ax[0, 1].set_xlabel('sepal len')

ax[1, 0].bar(df['species'], df['petal_width'])


ax[1, 0].set_xlabel('Sepal width')

ax[1, 1].hist(df['petal_length'], color='orange',


edgecolor='white', bins=[1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5,
ax[1, 1].set_xlabel('petal len')
[Link]()
In [ ]: fig = [Link](figsize=(15, 10))

ax1 = fig.add_subplot(2, 2, 1)
[Link](df['sepal_length'], df['petal_length'])
ax1.set_xlabel('sepal length')

ax2 = fig.add_subplot(2, 2, 2)
[Link](df['sepal_width'], df['petal_width'])
ax2.set_xlabel('sepal width')

ax3 = fig.add_subplot(2, 2, 3)
[Link](df['sepal_length'], df['sepal_width'], color='green')
ax3.set_xlabel('sepal len')

ax4 = fig.add_subplot(2, 2, 4)
[Link](df['petal_length'], color='orange',
edgecolor='white', bins=[1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5,
ax4.set_xlabel('petal len')

[Link]()

In [ ]: [Link]('ggplot')

**3D Scatter Plot**


In [ ]: fig = [Link](figsize=(10, 6))

ax = [Link](projection='3d')
ax.scatter3D(df['sepal_length'], df['sepal_width'],
df['petal_length'], marker='>', s=50)
ax.set_xlabel('sepal len')
ax.set_ylabel('sepal width')
ax.set_zlabel('petal len')
[Link]()
In [ ]: x = [0, 1, 5]
y = [0, 10, 13]
z = [0, 13, 20]

[Link](figsize=(10, 6))

ax = [Link](projection='3d')
[Link](x, y, z, s=70)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

[Link]()

3D Line Plot
In [ ]: x = [0, 1, 5, 25]
y = [0, 10, 13, 0]
z = [0, 13, 20, 9]

[Link](figsize=(10, 6))

ax = [Link](projection='3d')
[Link](x, y, z, s=100, color='red')
[Link](x, y, z)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

[Link]()

**3D Surface Plots**


In [ ]: x = [Link](-10, 10, 100)
y = [Link](-10, 10, 100)

xx, yy = [Link](x, y)
[Link]

(100, 100)
Out[ ]:

In [ ]: z = xx**2 + yy**2

In [ ]: fig = [Link](figsize=(10, 6))

ax = [Link](projection='3d')

p = ax.plot_surface(xx, yy, z, cmap='viridis')

[Link](p)
[Link]()

C:\Users\dhanr\AppData\Local\Temp\ipykernel_23404\[Link]: Matplo
tlibDeprecationWarning: Auto-removal of grids by pcolor() and pcolormesh
() is deprecated since 3.5 and will be removed two minor releases later;
please call grid(False) first.
[Link](p)

**Contour Plots**
In [ ]: fig = [Link](figsize=(10, 6))

ax = [Link]()

p = [Link](xx, yy, z, cmap='viridis')


[Link](p)

[Link]()

C:\Users\dhanr\AppData\Local\Temp\ipykernel_23404\[Link]: Matplo
tlibDeprecationWarning: Auto-removal of grids by pcolor() and pcolormesh
() is deprecated since 3.5 and will be removed two minor releases later;
please call grid(False) first.
[Link](p)

Common questions

Powered by AI

Using Matplotlib's style settings like 'fivethirtyeight' and 'ggplot' helps to easily change the visual style of plots, aligning them with the aesthetics of these well-known visualization styles. This includes adjusting color palettes, fonts, and the presence of grid lines, leading to improved readability and appeal of the plots rendered .

Bar charts are used for categorical vs. numerical analysis, which makes them ideal for comparing different groups or categories against a numerical measure. Histograms, on the other hand, are used for univariate numerical analysis, presenting frequency distributions of a numerical variable. Bar charts offer insights into group aggregates, while histograms help to understand the data's distribution .

Setting axes limits focuses the viewer's attention on the most relevant data range, which is particularly helpful when there are outliers that might skew the visualization scale. An example in Matplotlib is limiting the y-axis to show prices only up to a certain threshold, effectively excluding extreme outlier values and offering a clearer view of typical data distribution .

Color and marker size are crucial in scatter plots as they help to distinguish between different data categories or to emphasize certain data points. For instance, using a color map makes it easier to visually identify clusters or trends, while varying marker size may indicate an additional dimension of data such as magnitude or frequency .

Contour plots in Matplotlib represent a 3D surface on a 2D plane, using lines to connect points of equal value, making it ideal for visualizing topographical maps or to show functions' value gradients. Unlike 3D visualizations which depict volume or structure within a perceptual space, contour plots simplify the representation, focusing on illustrating data intensity and gradients across the specified axis ranges .

Annotations enrich plot interpretability by providing direct explanatory notes on specific data points, which helps in drawing immediate conclusions. They are particularly beneficial in highlighting outliers, trends, or significant data entries that might otherwise be overlooked. This makes them useful in scenarios like financial analysis or research presentations where attention to detail is critical .

Matplotlib is a cross-platform plotting library for Python and its numerical extension NumPy, offering features similar to MATLAB's. However, Matplotlib serves as an open-source alternative, making it accessible without licensing fees associated with MATLAB. Moreover, Matplotlib can be seamlessly integrated with Python's rich ecosystem of scientific libraries like NumPy and pandas, facilitating data manipulation and analysis before visualization .

Pie charts uniquely contribute by allowing for quick visual comparison of parts to a whole, expressing relative proportions clearly within a single chart. This is particularly effective when there are a few categorical data points. While often criticized for difficulty in perceiving precise values and comparisons beyond about five categories, they effectively illustrate hierarchical data relationships on a standard scale .

3D plots, including scatter and surface plots, allow for the visualization of data relationships across three dimensions, providing a more comprehensive view of complex datasets. This aids in identifying patterns and correlations not observable in 2D plots. However, a potential downside is the increased complexity in interpretation, where overlapping points or surfaces might obscure insights, making them less ideal for non-expert audiences .

Using subplots in Matplotlib is preferable when presenting multiple datasets as it allows for side-by-side comparison of different aspects or metrics in a coherent manner within a single figure. Effective use requires consistent scales, clear labeling, and strategic layout to ensure that each subplot is individually understandable and collectively informative .

You might also like