Create Charts, Maps and Scatterplot Matrix with Plotly and Google Colab

Lisandro Abulatif
6 min readJun 3, 2023

--

Photo by Edmond Dantès

In the realm of data visualization, having a powerful and versatile tool is crucial for effectively communicating insights and discovering patterns in data. Plotly has emerged as a popular choice among data scientists and analysts, offering a comprehensive solution for creating visually stunning and informative graphs, charts, and dashboards.

Plotly distinguishes itself as an exceptional data visualization tool for several reasons. Firstly, its extensive library of chart types allows users to create a diverse range of visual representations, spanning from basic line plots and bar charts to intricate heatmaps and 3D surface plots. Moreover, Plotly’s interactive capabilities enable users to delve deeper into the data, zoom in on specific regions of interest, and gain detailed information by hovering over data points. The tool’s seamless integration with programming languages such as Python and R further enhances its appeal, as users can leverage their coding skills to generate dynamic visualizations effortlessly.

Examples of Plotly in Action:

Let’s explore some practical use cases that highlight the power of Plotly for data visualization. Consider analyzing stock market data and presenting the historical performance of a particular company’s stock. With Plotly, you can create an interactive candlestick chart that showcases the opening, closing, high, and low prices for each trading day. Users can zoom in on specific time periods, compare multiple stocks, and even incorporate trend lines or moving averages for advanced analysis.

Another compelling application of Plotly is geographical data visualization. Imagine studying population density across different countries. Plotly’s choropleth maps offer an effective way to visualize this data, utilizing color-coding to represent population density levels in each country. By hovering over individual countries, users can access specific values and gain insights into population distribution trends.

These examples provide a glimpse into the capabilities of Plotly. Through its versatility, interactive features, and extensive customization options, Plotly empowers data professionals to create captivating visualizations that breathe life into data, driving informed decision-making processes.

In this blog post, is to guide you through the process of easily getting started with Plotly in Google Colab, a popular Python environment for data analysis, which is free and easy to use.

Let’s have hands dirty!

Step 1: Setting Up Google Colab

Begin by opening Google Colab in your web browser and creating a new notebook. Google Colab provides a convenient environment for running Python code, and it comes pre-installed with many useful libraries, including Plotly. This eliminates the need for manual installation and allows you to dive straight into data visualization.

Google Colab

Click on “new notebook”.

Step 2: Importing the Plotly Library

To start using Plotly, import the library into your Colab notebook. Use the following code snippet:

import plotly.express as px

This imports the necessary module from Plotly and prepares the environment for creating visualizations.

Step 3: Creating a Pie Chart

Let’s explore creating a pie chart with Plotly. Suppose you have a dataset containing the sales percentages of different product categories. Use the following code:

# Create data
categories = ['Food', 'Rent', 'Transportation']
expenses = [500, 800, 300]

# Create a Pie Chart
fig = px.pie(names=categories, values=expenses, title="Pie Chart Title")

# Display the chart
fig.show()

This code snippet utilizes the px.pie function from Plotly Express to create a Pie Chart. By specifying the names of the categories and their corresponding values, you can easily visualize the expense distribution. Calling fig.show() displays the Pie Chart in the output.

Step 4: Creating a Choropleth Map

Now, let’s explore creating a Choropleth Map using Plotly Express. Suppose you have a dataset with information about the urban population density of different countries in Europe. Use the following code:

# Load the dataset
data = px.data.gapminder().query("continent == 'Europe'")

# Create a Choropleth Map
fig = px.choropleth(data_frame=data,
locations='iso_alpha',
color='pop',
hover_name='country',
title='Urban Population in Europe',
color_continuous_scale='blues')

# Set the map layout
fig.update_geos(
visible=False,
resolution=50,
showcountries=True,
countrycolor="gray",
showcoastlines=True,
coastlinecolor="white",
projection_type="natural earth",
lataxis_range=[35, 75],
lonaxis_range=[-25, 50]
)

# Display the map
fig.show()

This code snippet utilizes the px.choropleth function from Plotly Express to create a Choropleth Map. By providing the dataset, the column names for locations and colors, and specifying the location mode, you can easily visualize the population density of different countries. Calling fig.show() displays the Choropleth Map in the output.

Step 4: Creating a Scatter Matrix

Now, let’s explore creating a Scatter Matrix using Plotly Express. Suppose you have a dataset with information about Country GDP, Country Population, Country Vehicles fleet, for some countries in Europe. Use the following code:

# Create a sample dataframe
data = {
"Country": ["Germany", "France", "Italy", "Spain", "United Kingdom"],
"GDP": [3.8, 2.7, 1.9, 1.4, 2.1],
"Population": [83, 67, 60, 47, 66],
"Vehicles Fleet": [50, 35, 40, 30, 45]
}

df = pd.DataFrame(data)

# Create a scatter matrix
fig = px.scatter_matrix(df,
dimensions=["GDP", "Population", "Vehicles Fleet"],
color="Country",
title="Scatter Matrix: Country GDP, Population, and Vehicles Fleet in Europe")

# Display the scatter matrix
fig.show()

In this code, we create a sample dataframe df with columns "Country", "GDP", "Population", and "Vehicles Fleet" containing data for five European countries. You can replace this sample data with your own dataset by loading it into a dataframe.

We then create the scatter matrix using px.scatter_matrix(). We specify the dimensions as a list of column names ("GDP", "Population", "Vehicles Fleet") and set the color based on the "Country" column. We also provide a title for the scatter matrix.

Finally, we call fig.show() to display the scatter matrix in the output.

You can customize the code by replacing the sample data with your own data and adjusting the column names accordingly.

Some reasons I’m recommending Plotly

  1. Interactive and Dynamic Visualizations: With Plotly and Google Colab, you can create interactive and dynamic visualizations that bring your data to life. From zooming and panning to hovering and tooltips, Plotly’s interactivity enables you to explore your data in an engaging and immersive way. Gone are the days of static plots; with Plotly and Google Colab, you can interact with your visualizations, gaining deeper insights and effectively conveying your findings.
  2. Versatility at Your Fingertips: Plotly offers a vast array of chart types, allowing you to effectively represent and communicate your data. Whether you’re working with line charts, scatter plots, heatmaps, or choropleth maps, Plotly has you covered. With Google Colab’s integration, you can seamlessly leverage Plotly’s versatility to create stunning visualizations tailored to your specific needs. Customize your plots with ease, adding stylistic elements that enhance the visual appeal and clarity of your charts.
  3. Harmonious Python Integration: As a Python library, Plotly integrates seamlessly with Google Colab’s Python environment. This integration empowers you to combine the power of Python’s data manipulation and analysis capabilities with Plotly’s visualization prowess. With Google Colab’s ability to run Python code cells, you can streamline your workflow, performing data preprocessing, analysis, and visualization in a single notebook. This unified environment allows for efficient iteration, making it easier than ever to create and refine your visualizations.
  4. Collaboration and Sharing Made Simple: Google Colab’s collaborative features make it an ideal platform for teamwork and knowledge sharing. When you combine Plotly with Google Colab, you can create interactive and visually captivating visualizations that can be easily shared and accessed by your team members or stakeholders. Plotly’s export options enable you to save your visualizations in various formats, empowering you to present your findings in reports, embed them in web applications, or share them as interactive HTML files.

Conclusion

By following these steps, you can easily start using Plotly for data visualization in Google Colab. Whether you want to create pie charts, choropleth maps, or explore other types of visualizations, Plotly provides a robust set of tools to bring your data to life. Experiment with different datasets and customization options to create visually appealing and informative visualizations that help you gain valuable insights from your data. So, get started and unleash the power of Plotly in your data visualization projects.

--

--

Lisandro Abulatif
Lisandro Abulatif

Written by Lisandro Abulatif

Data Analytics | Information for better decisions and assertive results.

No responses yet