Sharing is caring!

Lesson 3: Charts and Diagrams in Colab with Matplotlib

Table of Contents

Introduction

Hey there! So, you wanna get into charts and diagrams using Colaboratory, huh? It’s super fun and kinda like doodling but with data. We’re gonna use a bunch of tools to make some cool visuals.

Also, check:

Ready? Let’s go!

Matplotlib: The Old Reliable

Matplotlib is like that old friend who’s always got your back. You can make all sorts of charts with it. It’s simple and gets the job done.

Line Plots

Picture this. You’ve got some numbers, and you wanna see how they trend. Line plots are perfect for that!

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y1 = [1, 3, 5, 3, 1, 3, 5, 3, 1]
y2 = [2, 4, 6, 4, 2, 4, 6, 4, 2]
plt.plot(x, y1, label="line L")
plt.plot(x, y2, label="line H")
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.title("Line Graph Example")
plt.legend()
plt.show()

Bar Plots

Now, let’s talk bars. Not the kind you hang out in, but the kind you use to compare stuff.

import matplotlib.pyplot as plt

x1 = [1, 3, 4, 5, 6, 7, 9]
y1 = [4, 7, 2, 4, 7, 8, 3]
x2 = [2, 4, 6, 8, 10]
y2 = [5, 6, 2, 6, 2]
plt.bar(x1, y1, label="Blue Bar", color='b')
plt.bar(x2, y2, label="Green Bar", color='g')
plt.xlabel("bar number")
plt.ylabel("bar height")
plt.title("Bar Chart Example")
plt.legend()
plt.show()

Histograms

Ever wondered how your data piles up? Histograms are like data piles. They show you the frequency of your data points.

import matplotlib.pyplot as plt
import numpy as np

n = 5 + np.random.randn(1000)
m = [m for m in range(len(n))]
plt.bar(m, n)
plt.title("Raw Data")
plt.show()

plt.hist(n, bins=20)
plt.title("Histogram")
plt.show()

plt.hist(n, cumulative=True, bins=20)
plt.title("Cumulative Histogram")
plt.show()

Scatter Plots

Scatter plots are like star maps. They show relationships between two sets of data.

import matplotlib.pyplot as plt

x1 = [2, 3, 4]
y1 = [5, 5, 5]
x2 = [1, 2, 3, 4, 5]
y2 = [2, 3, 2, 3, 4]
y3 = [6, 8, 7, 8, 7]
plt.scatter(x1, y1)
plt.scatter(x2, y2, marker='v', color='r')
plt.scatter(x2, y3, marker='^', color='m')
plt.title('Scatter Plot Example')
plt.show()

Stack Plots

Imagine layers of cake. Stack plots show multiple datasets stacked on top of each other.

import matplotlib.pyplot as plt

idxes = [ 1,  2,  3,  4,  5,  6,  7,  8,  9]
arr1  = [23, 40, 28, 43,  8, 44, 43, 18, 17]
arr2  = [17, 30, 22, 14, 17, 17, 29, 22, 30]
arr3  = [15, 31, 18, 22, 18, 19, 13, 32, 39]
plt.plot([], [], color='r', label = 'D 1')
plt.plot([], [], color='g', label = 'D 2')
plt.plot([], [], color='b', label = 'D 3')
plt.stackplot(idxes, arr1, arr2, arr3, colors= ['r', 'g', 'b'])
plt.title('Stack Plot Example')
plt.legend()
plt.show()

Pie Charts

Pie charts are like, well, pies. They show parts of a whole.

import matplotlib.pyplot as plt

labels = 'S1', 'S2', 'S3'
sections = [56, 66, 24]
colors = ['c', 'g', 'y']
plt.pie(sections, labels=labels, colors=colors, startangle=90, explode = (0, 0.1, 0), autopct = '%1.2f%%')
plt.axis('equal')
plt.title('Pie Chart Example')
plt.show()

fill_between and alpha

This one’s neat. Fill between lines to highlight areas.

import matplotlib.pyplot as plt
import numpy as np

ys = 200 + np.random.randn(100)
x = [x for x in range(len(ys))]
plt.plot(x, ys, '-')
plt.fill_between(x, ys, 195, where=(ys > 195), facecolor='g', alpha=0.6)
plt.title("Fills and Alpha Example")
plt.show()

Subplotting using Subplot2grid

Subplots are like a grid of small charts. Handy for comparing stuff side by side.

import matplotlib.pyplot as plt
import numpy as np

def random_plots():
  xs = []
  ys = []

  for i in range(20):
    x = i
    y = np.random.randint(10)

    xs.append(x)
    ys.append(y)

  return xs, ys

fig = plt.figure()
ax1 = plt.subplot2grid((5, 2), (0, 0), rowspan=1, colspan=2)
ax2 = plt.subplot2grid((5, 2), (1, 0), rowspan=3, colspan=2)
ax3 = plt.subplot2grid((5, 2), (4, 0), rowspan=1, colspan=1)
ax4 = plt.subplot2grid((5, 2), (4, 1), rowspan=1, colspan=1)

x, y = random_plots()
ax1.plot(x, y)

x, y = random_plots()
ax2.plot(x, y)

x, y = random_plots()
ax3.plot(x, y)

x, y = random_plots()
ax4.plot(x, y)

plt.tight_layout()
plt.show()

Seaborn: The Stylish One

Seaborn is like Matplotlib’s cool cousin. It’s got style!

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

num_points = 20
x = 5 + np.arange(num_points) + np.random.randn(num_points)
y = 10 + np.arange(num_points) + 5 * np.random.randn(num_points)
sns.regplot(x, y)
plt.show()

3D Graphs: Next-Level Cool

3D Scatter Plots

Let’s add a dimension. 3D scatter plots show relationships in three dimensions.

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import axes3d

fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')

x1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y1 = np.random.randint(10, size=10)
z1 = np.random.randint(10, size=10)

x2 = [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
y2 = np.random.randint(-10, 0, size=10)
z2 = np.random.randint(10, size=10)

ax.scatter(x1, y1, z1, c='b', marker='o', label='blue')
ax.scatter(x2, y2, z2, c='g', marker='D', label='green')

ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_zlabel('z axis')
plt.title("3D Scatter Plot Example")
plt.legend()
plt.tight_layout()
plt.show()

3D Bar Plots

3D bar plots are like regular bar plots but way cooler.

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = np.random.randint(10, size=10)
z = np.zeros(10)

dx = np.ones(10)
dy = np.ones(10)
dz = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

ax.bar3d(x, y, z

, dx, dy, dz, color='g')

ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_zlabel('z axis')
plt.title("3D Bar Chart Example")
plt.tight_layout()
plt.show()

Wireframe Plots

Wireframe plots look like 3D blueprints.

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')

x, y, z = axes3d.get_test_data()

ax.plot_wireframe(x, y, z, rstride = 2, cstride = 2)

plt.title("Wireframe Plot Example")
plt.tight_layout()
plt.show()

Altair: The Interactive Whiz

Altair makes interactive charts. Check this out.

import altair as alt
from vega_datasets import data
cars = data.cars()

alt.Chart(cars).mark_point().encode(
    x='Horsepower',
    y='Miles_per_Gallon',
    color='Origin',
).interactive()

Plotly: The Fancy One

Sample

Plotly makes fancy interactive charts too. Here’s a contour plot.

from plotly.offline import iplot
import plotly.graph_objs as go

data = [
    go.Contour(
        z=[[10, 10.625, 12.5, 15.625, 20],
           [5.625, 6.25, 8.125, 11.25, 15.625],
           [2.5, 3.125, 5., 8.125, 12.5],
           [0.625, 1.25, 3.125, 6.25, 10.625],
           [0, 0.625, 2.5, 5.625, 10]]
    )
]
iplot(data)

Bokeh: The Beautiful

Bokeh is another one for beautiful, interactive plots.

import numpy as np
from bokeh.plotting import figure, show
from bokeh.io import output_notebook

output_notebook()

N = 4000
x = np.random.random(size=N) * 100
y = np.random.random(size=N) * 100
radii = np.random.random(size=N) * 1.5
colors = ["#%02x%02x%02x" % (r, g, 150) for r, g in zip(np.floor(50+2*x).astype(int), np.floor(30+2*y).astype(int))]

p = figure()
p.circle(x, y, radius=radii, fill_color=colors, fill_alpha=0.6, line_color=None)
show(p)

Explanation of Matplotlib

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. It is especially useful for creating plots quickly and efficiently.

Line Plots

Line plots are used to display data points connected by straight lines. They are great for showing trends over time.

  • x and y are lists of data points.
  • plt.plot() creates a line plot.
  • plt.xlabel() and plt.ylabel() label the axes.
  • plt.title() sets the title of the plot.
  • plt.legend() adds a legend to the plot.
  • plt.show() displays the plot.

Bar Plots

Bar plots are used to compare different categories or groups.

  • plt.bar() creates a bar plot.
  • color parameter changes the color of the bars.
  • Other functions like plt.xlabel(), plt.ylabel(), plt.title(), and plt.legend() work the same way as in line plots.

Histograms

Histograms are used to represent the distribution of a dataset.

  • plt.hist() creates a histogram.
  • bins parameter specifies the number of bins.
  • cumulative parameter can be set to True for a cumulative histogram.

Scatter Plots

Scatter plots are used to display values for typically two variables for a set of data.

  • plt.scatter() creates a scatter plot.
  • marker and color parameters customize the appearance of points.

Stack Plots

Stack plots show multiple datasets stacked on top of each other, useful for visualizing cumulative data.

  • plt.stackplot() creates a stack plot.
  • colors parameter specifies colors for the layers.

Pie Charts

Pie charts are used to show proportions of a whole.

  • plt.pie() creates a pie chart.
  • labels assigns labels to each section.
  • colors parameter changes the color of the sections.
  • autopct shows percentages.

fill_between and alpha

fill_between is used to fill the area between two horizontal curves.

  • plt.fill_between() fills the area between lines.
  • alpha parameter sets transparency.

Subplotting using Subplot2grid

Subplots are useful for comparing multiple plots in a single figure.

  • plt.subplot2grid() creates a subplot grid.
  • rowspan and colspan parameters specify the size of the subplot within the grid.

Seaborn: The Stylish One

Seaborn is a data visualization library based on Matplotlib that provides a high-level interface for drawing attractive statistical graphics.

Example

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

num_points = 20
x = 5 + np.arange(num_points) + np.random.randn(num_points)
y = 10 + np.arange(num_points) + 5 * np.random.randn(num_points)
sns.regplot(x, y)
plt.show()
  • sns.regplot() creates a scatter plot with a regression line.
  • plt.show() displays the plot.

3D Graphs: Next-Level Cool

3D graphs are useful for visualizing three-dimensional data.

3D Scatter Plots

3D scatter plots display relationships in three dimensions.

  • ax.scatter() creates a 3D scatter plot.
  • ax.set_xlabel(), ax.set_ylabel(), and ax.set_zlabel() label the axes.

3D Bar Plots

3D bar plots are like regular bar plots but in three dimensions.

  • ax.bar3d() creates a 3D bar plot.

Wireframe Plots

Wireframe plots look like 3D blueprints.

  • ax.plot_wireframe() creates a wireframe plot.

Altair: The Interactive Whiz

Altair is a declarative statistical visualization library for Python, based on Vega and Vega-Lite.

Example

import altair as alt
from vega_datasets import data
cars = data.cars()

alt.Chart(cars).mark_point().encode(
    x='Horsepower',
    y='Miles_per_Gallon',
    color='Origin',
).interactive()
  • alt.Chart() creates a chart object.
  • mark_point() specifies the type of plot (scatter plot).
  • encode() maps data to visual properties.
  • .interactive() makes the chart interactive.

Plotly: The Fancy One

Plotly is a graphing library that makes interactive, publication-quality graphs.

Example

from plotly.offline import iplot
import plotly.graph_objs as go

data = [
    go.Contour(
        z=[[10, 10.625, 12.5, 15.625, 20],
           [5.625, 6.25, 8.125, 11.25, 15.625],
           [2.5, 3.125, 5., 8.125, 12.5],
           [0.625, 1.25, 3.125, 6.25, 10.625],
           [0, 0.625, 2.5, 5.625, 10]]
    )
]
iplot(data)
  • go.Contour() creates a contour plot.
  • iplot() displays the plot in an interactive format.

Bokeh: The Beautiful

Bokeh is a library for creating interactive visualizations for modern web browsers.

Example

import numpy as np
from bokeh.plotting import figure, show
from bokeh.io import output_notebook

output_notebook()

N = 4000
x = np.random.random(size=N) * 100
y = np.random.random(size=N) * 100
radii = np.random.random(size=N) * 1.5
colors = ["#%02x%02x%02x" % (r, g, 150) for r, g in zip(np.floor(50+2*x).astype(int), np.floor(30+2*y).astype(int))]

p = figure()
p.circle(x, y, radius=radii, fill_color=colors, fill_alpha=0.6, line_color=None)
show(p)
  • figure() creates a new plot.
  • p.circle() adds circle glyphs to the plot.
  • show() displays the plot.

Now you have a comprehensive guide to creating various types of charts and diagrams using different libraries in Colab. Happy plotting!

Can I use matplotlib in Google Colab?

Yes, you can use Matplotlib in Google Colab! It’s a popular choice for data visualization in Python and works seamlessly within Colab notebooks. Here’s a quick guide on how to get started with Matplotlib in Google Colab.

Step-by-Step Guide to Using Matplotlib in Google Colab

Setting Up Your Environment

First, make sure you have the necessary imports:

import matplotlib.pyplot as plt

This line imports Matplotlib’s pyplot module, which is the interface used for creating plots.

Creating a Simple Line Plot

Let’s start with a basic example of a line plot.

# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

# Create the plot
plt.plot(x, y)

# Add titles and labels
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.title("Simple Line Plot")

# Display the plot
plt.show()

When you run this code in a Colab cell, you’ll see a simple line plot displayed in the output.

More Advanced Plots

You can create more complex plots with multiple lines, bar charts, scatter plots, and more. Here are a few examples:

Multiple Line Plot
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 8, 27, 64, 125]

plt.plot(x, y1, label="Line 1")
plt.plot(x, y2, label="Line 2")

plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.title("Multiple Line Plot")
plt.legend()

plt.show()
Bar Chart
# Sample data
x = ['A', 'B', 'C', 'D']
y = [3, 7, 2, 5]

# Create the bar chart
plt.bar(x, y)

# Add titles and labels
plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Bar Chart Example")

# Display the plot
plt.show()
Scatter Plot
# Sample data
x = [5, 7, 8, 5, 6, 7]
y = [7, 8, 2, 4, 7, 3]
colors = [100, 200, 300, 400, 500, 600]
sizes = [20, 50, 80, 200, 500, 1000]

# Create the scatter plot
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='viridis')

# Add titles and labels
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.title("Scatter Plot Example")

# Display the plot
plt.show()

Customizing Your Plots

Matplotlib allows for extensive customization. You can change colors, add gridlines, annotate points, and much more. Here’s an example of customizing a plot with gridlines and annotations:

x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]

plt.plot(x, y, marker='o', linestyle='--', color='r')

plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.title("Customized Plot")

# Adding grid
plt.grid(True)

# Annotating a point
plt.annotate('Peak', xy=(4, 16), xytext=(3, 10),
             arrowprops=dict(facecolor='black', shrink=0.05))

plt.show()

It’s easy and powerful to use Matplotlib in Google Colab. You can visualize data, customize plots, and create various types of charts quickly.

Whether you’re doing simple or complex visualizations, Matplotlib in Colab ensures a smooth and efficient process.

So, get started with plotting your data using Matplotlib in Google Colab and bring your data to life!

How to make graphs in Colab?

Making graphs in Google Colab is easy and fun. Colab supports various libraries for data visualization, but Matplotlib is one of the most popular and versatile ones.

Getting Started

First, you need to import the Matplotlib library. Here’s how you do it:

import matplotlib.pyplot as plt

Creating Different Types of Graphs

Line Plot

Line plots are great for visualizing trends over time or continuous data. Here’s how you can create a simple line plot:

# Sample data
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]

# Create the plot
plt.plot(x, y)

# Add titles and labels
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.title("Simple Line Plot")

# Display the plot
plt.show()

Bar Chart

Bar charts are useful for comparing categorical data. Here’s how to create a bar chart:

# Sample data
categories = ['A', 'B', 'C', 'D']
values = [3, 7, 2, 5]

# Create the bar chart
plt.bar(categories, values)

# Add titles and labels
plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Bar Chart Example")

# Display the plot
plt.show()

Histogram

Histograms are used to represent the distribution of data. Here’s an example:

import numpy as np

# Generate random data
data = np.random.randn(1000)

# Create the histogram
plt.hist(data, bins=30, edgecolor='black')

# Add titles and labels
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.title("Histogram Example")

# Display the plot
plt.show()

Scatter Plot

Scatter plots show the relationship between two variables. Here’s how to create one:

# Sample data
x = [5, 7, 8, 5, 6, 7]
y = [7, 8, 2, 4, 7, 3]
sizes = [20, 50, 80, 200, 500, 1000]
colors = [10, 20, 30, 40, 50, 60]

# Create the scatter plot
plt.scatter(x, y, s=sizes, c=colors, alpha=0.5, cmap='viridis')

# Add titles and labels
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.title("Scatter Plot Example")

# Display the plot
plt.show()

Pie Chart

Pie charts are great for showing proportions. Here’s an example:

# Sample data
labels = 'A', 'B', 'C', 'D'
sizes = [15, 30, 45, 10]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0.1, 0, 0, 0)  # explode the first slice

# Create the pie chart
plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140)

# Equal aspect ratio ensures that pie is drawn as a circle.
plt.axis('equal')

# Add title
plt.title("Pie Chart Example")

# Display the plot
plt.show()

Customizing Plots

Matplotlib allows extensive customization of plots. Here’s an example of a customized plot:

# Sample data
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]

plt.plot(x, y, marker='o', linestyle='--', color='r', label='Data Line')

plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.title("Customized Plot")

# Adding a grid
plt.grid(True)

# Adding a legend
plt.legend()

# Display the plot
plt.show()

Working with Matplotlib in Google Colab is simple yet robust. You have the ability to generate various types of charts, ranging from basic line plots to intricate visual representations, using only a handful of lines of code.

Whether you’re analyzing data, putting together a slideshow, or delving into data exploration, Matplotlib in Colab proves to be an invaluable resource.

How to plot graphs with matplotlib?

Here is an example that will show you how to create a line plot, bar chart, histogram, scatter plot, and pie chart all in one go, demonstrating the versatility of Matplotlib.

# Importing necessary libraries
import matplotlib.pyplot as plt
import numpy as np

# Data for plots
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# Create subplots
fig, axs = plt.subplots(3, 2, figsize=(15, 15))

# Line plot
axs[0, 0].plot(x, y1, label='Sine wave', color='b')
axs[0, 0].plot(x, y2, label='Cosine wave', color='r')
axs[0, 0].set_title('Line Plot')
axs[0, 0].set_xlabel('X Axis')
axs[0, 0].set_ylabel('Y Axis')
axs[0, 0].legend()
axs[0, 0].grid(True)

# Bar chart
categories = ['A', 'B', 'C', 'D']
values = [3, 7, 2, 5]
axs[0, 1].bar(categories, values, color=['blue', 'green', 'red', 'purple'])
axs[0, 1].set_title('Bar Chart')
axs[0, 1].set_xlabel('Categories')
axs[0, 1].set_ylabel('Values')

# Histogram
data = np.random.randn(1000)
axs[1, 0].hist(data, bins=30, edgecolor='black', color='c')
axs[1, 0].set_title('Histogram')
axs[1, 0].set_xlabel('Value')
axs[1, 0].set_ylabel('Frequency')

# Scatter plot
x_scatter = [5, 7, 8, 5, 6, 7]
y_scatter = [7, 8, 2, 4, 7, 3]
sizes = [20, 50, 80, 200, 500, 1000]
colors = [10, 20, 30, 40, 50, 60]
scatter = axs[1, 1].scatter(x_scatter, y_scatter, s=sizes, c=colors, alpha=0.5, cmap='viridis')
axs[1, 1].set_title('Scatter Plot')
axs[1, 1].set_xlabel('X Axis')
axs[1, 1].set_ylabel('Y Axis')
fig.colorbar(scatter, ax=axs[1, 1])

# Pie chart
labels = 'A', 'B', 'C', 'D'
sizes = [15, 30, 45, 10]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0.1, 0, 0, 0)  # explode the first slice
axs[2, 0].pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140)
axs[2, 0].axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
axs[2, 0].set_title('Pie Chart')

# Turn off the 6th subplot (bottom-right empty plot)
axs[2, 1].axis('off')

# Adjust layout
plt.tight_layout()

# Show plot
plt.show()

Explanation

  • Line Plot: Demonstrates a sine and cosine wave.
  • Bar Chart: Shows values for different categories.
  • Histogram: Displays the distribution of random data.
  • Scatter Plot: Illustrates a scatter plot with varying sizes and colors.
  • Pie Chart: Represents proportions of different categories.

Running the Code

You can easily copy and paste this code into a Google Colab notebook cell and run it to observe the various types of plots generated.

This extensive example provides a great overview of the capabilities of Matplotlib and demonstrates how you can utilize it to create a wide range of visualizations.

How to create charts in matplotlib?

Here’s a combined example that includes multiple types of charts in a single script:

import matplotlib.pyplot as plt
import numpy as np

# Data for plots
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# Create subplots
fig, axs = plt.subplots(3, 2, figsize=(15, 15))

# Line plot
axs[0, 0].plot(x, y1, label='Sine wave', color='b')
axs[0, 0].plot(x, y2, label='Cosine wave', color='r')
axs[0, 0].set_title('Line Plot')
axs[0, 0].set_xlabel('X Axis')
axs[0, 0].set_ylabel('Y Axis')
axs[0, 0].legend()
axs[0, 0].grid(True)

# Bar chart
categories = ['A', 'B', 'C', 'D']
values = [3, 7, 2, 5]
axs[0, 1].bar(categories, values, color=['blue', 'green', 'red', 'purple'])
axs[0, 1].set_title('Bar Chart')
axs[0, 1].set_xlabel('Categories')
axs[0, 1].set_ylabel('Values')

# Histogram
data = np.random.randn(1000)
axs[1, 0].hist(data, bins=30, edgecolor='black', color='c')
axs[1, 0].set_title('Histogram')
axs[1, 0].set_xlabel('Value')
axs[1, 0].set_ylabel('Frequency')

# Scatter plot
x_scatter = [5, 7, 8, 5, 6, 7]
y_scatter = [7, 8, 2, 4, 7, 3]
sizes = [20, 50, 80, 200, 500, 1000]
colors = [10, 20, 30, 40, 50, 60]
scatter = axs[1, 1].scatter(x_scatter, y_scatter, s=sizes, c=colors, alpha=0.5, cmap='viridis')
axs[1, 1].set_title('Scatter Plot')
axs[1, 1].set_xlabel('X Axis')
axs[1, 1].set_ylabel('Y Axis')
fig.colorbar(scatter, ax=axs[1, 1])

# Pie chart
labels = 'A', 'B', 'C', 'D'
sizes = [15, 30, 45, 10]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0.1, 0, 0, 0)  # explode the first slice
axs[2, 0].pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140)
axs[2, 0].axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
axs[2, 0].set_title('Pie Chart')

# Turn off the 6th subplot (bottom-right empty plot)
axs[2, 1].axis('off')

# Adjust layout
plt.tight_layout()

# Show plot
plt.show()

Generating charts in Matplotlib requires a few simple steps: importing the library, preparing the data, creating the plot, and customizing it with titles, labels, and other elements.

Whether you’re visualizing line graphs, bar charts, histograms, scatter plots, or pie charts, Matplotlib in Google Colab offers a straightforward and efficient solution.

Conclusion

And there you have it, folks! We’ve just taken an exciting journey into the world of data visualization in Google Colab. We’ve explored a variety of tools and libraries that can bring your data to life with beautiful charts and diagrams.

Here are some key takeaways:

  • Matplotlib: This is your go-to tool for quick and versatile plotting. Whether you need line plots, bar charts, or even pie charts, Matplotlib has got you covered.
  • Seaborn: When you want to add some extra style and statistical insight to your plots, Seaborn is the way to go. It can make your plots not only functional but also visually appealing.
  • 3D Graphs: Sometimes, you need to venture beyond the flatland and into the world of three dimensions. That’s where Matplotlib’s 3D plotting capabilities come in handy.
  • Altair: If you love interactivity, Altair is the tool for you. It makes creating interactive charts a breeze, allowing you to engage more deeply with your data.
  • Plotly: For fancy and interactive visuals that are perfect for publication-quality outputs, Plotly is the way to go. It has all the bells and whistles to make your data shine.
  • Bokeh: If you’re looking to create beautiful and interactive plots for the modern web, Bokeh is the tool you need. It can help you create engaging and visually stunning visualizations.

In conclusion, data visualization is like magic. It transforms raw numbers into stories, patterns, and insights. Whether you’re just starting with a simple line plot or diving deep into interactive 3D visualizations, these tools provide a rich playground for your data adventures.

Remember, the best visualizations are not just about the code or the tool, but about the clarity and insight they bring to your audience. So go ahead, experiment, explore, and most importantly, have fun with your data!

Happy plotting! Fire up Google Colab and start creating your data stories today. With these tools in your toolkit, you’re well on your way to becoming a data visualization wizard.

Whether it’s for a school project, a business presentation, or just for fun, the sky’s the limit!


5 Comments

Lesson 4: Best Forms In Google Colab With Python Vs R · May 22, 2024 at 11:53 am

[…] Lesson 3: Charts and Diagrams in Colab with Matplotlib […]

Lesson 1: What Are Pandas Used For? Best Pandas Tips · May 22, 2024 at 12:21 pm

[…] Lesson 3: Charts and Diagrams in Colab with Matplotlib […]

Lesson 5: Best Guide Local Files, Drive, Sheets, And Cloud · May 22, 2024 at 9:27 pm

[…] Lesson 3: Charts and Diagrams in Colab with Matplotlib […]

Machine Learning Project 1: Honda Motor Stocks Best Prices · May 23, 2024 at 6:44 pm

[…] Lesson 3: Charts and Diagrams in Colab with Matplotlib […]

Lesson 6: Best BigQuery With Pandas Guide · October 24, 2024 at 10:29 am

[…] Lesson 3: Charts and Diagrams in Colab with Matplotlib […]

Leave a Reply

Avatar placeholder

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