Home Backend Development Python Tutorial Streamlit Part Mastering Data Visualization and Chart Types

Streamlit Part Mastering Data Visualization and Chart Types

Oct 30, 2024 am 06:20 AM

Streamlit Part Mastering Data Visualization and Chart Types

In today's fast-paced world of data science, effectively visualizing data is crucial. Whether you're an experienced data analyst or just starting your journey, mastering various visualization techniques can greatly enhance your ability to communicate insights and drive decision-making. This comprehensive guide explores Streamlit, a popular Python library for creating interactive web applications, and introduces 12 powerful chart types you can easily create to visualize your data. From simple bar charts to advanced geospatial visualizations, this tutorial covers it all.


Introduction to Streamlit and Its Visualization Capabilities

Streamlit has revolutionized the way data scientists and developers create interactive web applications for data visualization. With its intuitive API and seamless integration with popular Python libraries, Streamlit allows you to transform your data scripts into sharable web apps in minutes. In this guide, we'll focus on Streamlit's versatility in creating various chart types, each tailored to different data visualization needs.


1. Area Chart

Introduction to Area Charts

Area charts are excellent for displaying cumulative totals over time or across categories. They emphasize the magnitude of change and the relationship between different datasets, making them perfect for tracking trends and comparing multiple data series.

Creating the Area Chart

import numpy as np
import pandas as pd
import streamlit as st

st.write("### 1. Area Chart")

# Generate random data for the area chart
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=["col1", "col2", "col3"],
)

# Create an area chart using the random data
st.area_chart(
    chart_data,
    x="col1",
    y=["col2", "col3"],
    color=["#FF0000", "#0000FF"],
)

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Use Cases

  • Sales Growth: Visualize how sales increase over different quarters.
  • Website Traffic: Track the number of visitors over time.
  • Cumulative Metrics: Display cumulative metrics like total revenue or expenses.

Customization Tips

  • Adjust Colors: Modify the color parameter to match your brand or preferences.
  • Add Titles and Labels: Enhance clarity by adding titles and axis labels.
  • Modify Axes: Adjust the scale or range of the axes for better data representation.

2. Bar Chart

Introduction to Bar Charts

Bar charts are a fundamental way to compare different categories or groups. They are highly effective in displaying discrete data points, making it easy to compare quantities across various categories.

Creating the Bar Chart

import numpy as np
import pandas as pd
import streamlit as st

st.write("### 1. Area Chart")

# Generate random data for the area chart
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=["col1", "col2", "col3"],
)

# Create an area chart using the random data
st.area_chart(
    chart_data,
    x="col1",
    y=["col2", "col3"],
    color=["#FF0000", "#0000FF"],
)

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Use Cases

  • Sales by Region: Compare sales figures across different regions.
  • Product Popularity: Display the popularity of various products.
  • Survey Results: Visualize responses to survey questions.

Customization Options

  • Bar Colors: Although the example uses default settings, you can customize bar colors using additional parameters or by preprocessing the data.
  • Orientation: Change the orientation of the bars (horizontal or vertical) for better readability.
  • Labels and Legends: Add labels and legends to provide more context to the data.

3. Line Chart

Introduction to Line Charts

Line charts are excellent for showing trends over continuous data, such as time series. They help in tracking changes, identifying patterns, and comparing multiple data series over the same interval.

Creating the Line Chart

import numpy as np
import pandas as pd
import streamlit as st

st.write("### 2. Bar Chart")

# Generate random data for the bar chart
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=["col1", "col2", "col3"],
)

# Display a bar chart using the same data
st.bar_chart(chart_data)

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Use Cases

  • Stock Prices: Track stock price movements over time.
  • Temperature Changes: Monitor temperature fluctuations across different days.
  • Website Visits: Analyze website traffic trends over weeks or months.

Customization Tips

  • Multiple Lines: Plot multiple lines by specifying additional columns in the y parameter.
  • Line Styles: Adjust line styles (solid, dashed) to differentiate between data series.
  • Interactivity: Enhance interactivity by adding tooltips or hover effects to display exact values.

4. Map

Introduction to Maps in Streamlit

Geographical data visualization is crucial for spatial analysis, allowing you to visualize data points on a map to identify patterns, hotspots, and distributions across different locations.

Creating the Map

import numpy as np
import pandas as pd
import streamlit as st

st.write("### 1. Area Chart")

# Generate random data for the area chart
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=["col1", "col2", "col3"],
)

# Create an area chart using the random data
st.area_chart(
    chart_data,
    x="col1",
    y=["col2", "col3"],
    color=["#FF0000", "#0000FF"],
)

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Use Cases

  • Store Locations: Display the locations of multiple stores or offices.
  • Event Hotspots: Visualize areas with high concentrations of events or activities.
  • Demographic Distributions: Show the distribution of different demographic groups across regions.

Customization Tips

  • Map Center and Zoom: Adjust the map's center and zoom level to focus on specific areas.
  • Marker Aesthetics: Customize marker shapes, sizes, and colors to represent different data dimensions.
  • Interactivity: Add tooltips or pop-ups to provide more information about each data point.

5. Scatter Chart

Introduction to Scatter Charts

Scatter charts are powerful tools for identifying relationships or correlations between two variables. They help in uncovering patterns, trends, and potential causations within your data.

Creating the Scatter Chart

import numpy as np
import pandas as pd
import streamlit as st

st.write("### 2. Bar Chart")

# Generate random data for the bar chart
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=["col1", "col2", "col3"],
)

# Display a bar chart using the same data
st.bar_chart(chart_data)

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Use Cases

  • Advertising vs. Sales: Explore the relationship between advertising spend and sales figures.
  • Height vs. Weight: Analyze the correlation between individuals' heights and weights.
  • Performance Metrics: Compare different performance metrics of products or services.

Customization Tips

  • Trend Lines: Add trend lines to highlight correlations or trends within the data.
  • Point Sizes and Colors: Differentiate data points by adjusting their sizes and colors based on additional variables.
  • Interactivity: Enhance interactivity by enabling tooltips that display detailed information when hovering over points.

6. Altair Chart

Introduction to Altair

Altair is a declarative statistical visualization library for Python, offering advanced charting capabilities with a simple and intuitive syntax. It excels in creating interactive and complex visualizations with minimal code.

Creating the Altair Chart

import numpy as np
import pandas as pd
import streamlit as st

st.write("### 1. Area Chart")

# Generate random data for the area chart
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=["col1", "col2", "col3"],
)

# Create an area chart using the random data
st.area_chart(
    chart_data,
    x="col1",
    y=["col2", "col3"],
    color=["#FF0000", "#0000FF"],
)

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Use Cases

  • Exploratory Data Analysis: Investigate relationships between multiple variables.
  • Interactive Dashboards: Create dynamic visualizations that respond to user inputs.
  • Detailed Statistical Visualizations: Present complex data in an understandable format.

Customization Tips

  • Faceting: Create small multiples to compare different subsets of data.
  • Mark Types: Experiment with different mark types like lines, bars, or areas for varied visual effects.
  • Interactive Elements: Incorporate selections, filters, and zooming to enhance user interactivity.

8. Graphviz Chart

Introduction to Graphviz

Graphviz is a tool for creating graph and network diagrams, making it invaluable for visualizing relationships, workflows, and organizational structures. It allows you to represent complex connections in a clear and organized manner.

Creating the Graphviz Chart

import numpy as np
import pandas as pd
import streamlit as st

st.write("### 2. Bar Chart")

# Generate random data for the bar chart
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=["col1", "col2", "col3"],
)

# Display a bar chart using the same data
st.bar_chart(chart_data)

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Use Cases

  • Software Development Pipelines: Visualize the stages of software development from planning to deployment.
  • Organizational Structures: Represent the hierarchy and relationships within an organization.
  • Decision Trees: Illustrate the flow of decisions and possible outcomes.

Customization Tips

  • Node Shapes and Colors: Customize node shapes and colors to represent different types of entities or statuses.
  • Edge Styles: Modify edge styles (dashed, bold) to indicate different types of relationships or dependencies.
  • Graph Layouts: Explore different graph layouts (e.g., hierarchical, circular) for better clarity.

9. Plotly Chart

Introduction to Plotly

Plotly is a powerful library for creating interactive and publication-quality graphs. It offers a wide range of chart types and customization options, making it suitable for complex data visualizations and interactive dashboards.

Creating Distribution Plots

import numpy as np
import pandas as pd
import streamlit as st

st.write("### 1. Area Chart")

# Generate random data for the area chart
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=["col1", "col2", "col3"],
)

# Create an area chart using the random data
st.area_chart(
    chart_data,
    x="col1",
    y=["col2", "col3"],
    color=["#FF0000", "#0000FF"],
)

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Creating Scatter Plots with Plotly Express

import numpy as np
import pandas as pd
import streamlit as st

st.write("### 2. Bar Chart")

# Generate random data for the bar chart
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=["col1", "col2", "col3"],
)

# Display a bar chart using the same data
st.bar_chart(chart_data)

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Use Cases

  • Distribution Analysis: Compare the distributions of different datasets side by side.
  • Interactive Dashboards: Create dynamic and interactive visualizations that respond to user inputs.
  • Comparative Analysis: Use multiple themes and styles to highlight different aspects of the data.

Customization Tips

  • Theme Adjustments: Explore different themes to match your application's design.
  • Layout Configurations: Adjust layout settings like margins, legends, and axis titles for better presentation.
  • Advanced Chart Types: Experiment with 3D plots, heatmaps, and other advanced chart types for more complex visualizations.

10. pydeck Chart

Introduction to pydeck

pydeck is a Python interface for deck.gl, enabling advanced, high-performance WebGL-powered visualizations. It is particularly useful for creating intricate and interactive geospatial visualizations.

Creating the pydeck Chart

import numpy as np
import pandas as pd
import streamlit as st

st.write("### 3. Line Chart")

# Generate random data for the line chart
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=["col1", "col2", "col3"],
)

# Create a line chart with the random data
st.line_chart(
    chart_data,
    x="col1",
    y="col2",
    color="col3",
)

st.write("#### 3.1 Basic Line Chart")

Copy after login

Use Cases

  • Geospatial Analysis: Visualize large geospatial datasets to identify patterns and hotspots.
  • Urban Planning: Analyze population density, traffic flow, or infrastructure distribution.
  • Environmental Studies: Map environmental data like pollution levels or wildlife sightings.

Customization Tips

  • Different Layer Types: Experiment with various layer types like ScatterplotLayer, ArcLayer, or PathLayer for diverse visual effects.
  • Map Styles: Change the map_style parameter to use different map themes (e.g., satellite, dark mode).
  • Interactivity: Enhance interactivity by enabling tooltips, filters, and dynamic data updates.

11. pyplot Chart

Introduction to Matplotlib's pyplot

Matplotlib is a foundational plotting library in Python, and pyplot provides a MATLAB-like interface for creating static, animated, and interactive visualizations. It is highly customizable and widely used for statistical data analysis and educational purposes.

Creating the Histogram

import numpy as np
import pandas as pd
import streamlit as st

st.write("### 1. Area Chart")

# Generate random data for the area chart
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=["col1", "col2", "col3"],
)

# Create an area chart using the random data
st.area_chart(
    chart_data,
    x="col1",
    y=["col2", "col3"],
    color=["#FF0000", "#0000FF"],
)

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Use Cases

  • Statistical Analysis: Visualize the distribution of datasets to identify patterns and anomalies.
  • Educational Purposes: Teach concepts like probability distributions and data normalization.
  • Data Exploration: Assess the shape and spread of data before performing further analysis.

Customization Options

  • Titles and Labels: Add titles, axis labels, and legends to provide context.
  • Colors and Styles: Customize bar colors, edge styles, and overall plot aesthetics.
  • Multiple Histograms: Overlay multiple histograms to compare different datasets or groups.
  • Advanced Features: Incorporate density plots, cumulative distributions, or annotations for deeper insights.

12. Vega Chart

Introduction to Vega-Lite

Vega-Lite is a high-level grammar for creating interactive visualizations, integrated into Streamlit for flexibility. It allows you to build sophisticated and responsive charts with concise specifications, making it easier to create complex visualizations without extensive coding.

Creating the Vega Chart

import numpy as np
import pandas as pd
import streamlit as st

st.write("### 2. Bar Chart")

# Generate random data for the bar chart
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=["col1", "col2", "col3"],
)

# Display a bar chart using the same data
st.bar_chart(chart_data)

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Use Cases

  • Sophisticated Interactive Visualizations: Create complex charts that respond to user interactions like hovering, clicking, or selecting.
  • Data Exploration: Enable users to explore datasets dynamically, uncovering insights through interactive elements.
  • Embedding Complex Charts: Integrate detailed and interactive charts within Streamlit apps for comprehensive data presentations.

Customization Tips

  • Adding Layers: Incorporate additional layers like lines, bars, or areas to enrich the visualization.
  • Custom Scales and Axes: Adjust scales, axis titles, and labels to improve readability and presentation.
  • Interactive Selections: Implement interactive selections and filters to allow users to focus on specific data subsets.
  • Styling and Themes: Enhance aesthetics by customizing colors, fonts, and overall theme settings.

Recap of Chart Types

In this tutorial, we've covered a diverse range of chart types available in Streamlit, each suited for different data visualization needs:

  1. Area Chart: Ideal for showing cumulative totals and trends.
  2. Bar Chart: Perfect for comparing discrete categories or groups.
  3. Line Chart: Excellent for tracking changes over continuous data like time series.
  4. Map: Essential for geographical data visualization and spatial analysis.
  5. Scatter Chart: Useful for identifying relationships and correlations between variables.
  6. Altair Chart: Advanced, interactive visualizations with declarative syntax.
  7. Graphviz Chart: Visualizing relationships and workflows through graph diagrams.
  8. Plotly Chart: Interactive and publication-quality graphs with extensive customization.
  9. pydeck Chart: High-performance geospatial visualizations using WebGL.
  10. pyplot Chart: Foundational plotting with Matplotlib's versatile capabilities.
  11. Vega Chart: Sophisticated interactive visualizations with Vega-Lite grammar.

? Get the Code: GitHub - jamesbmour/blog_tutorials
? Related Streamlit Tutorials:JustCodeIt
? Support my work: Buy Me a Coffee

The above is the detailed content of Streamlit Part Mastering Data Visualization and Chart Types. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Learning Python: Is 2 Hours of Daily Study Sufficient? Learning Python: Is 2 Hours of Daily Study Sufficient? Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python vs. C  : Understanding the Key Differences Python vs. C : Understanding the Key Differences Apr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Which is part of the Python standard library: lists or arrays? Which is part of the Python standard library: lists or arrays? Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python for Web Development: Key Applications Python for Web Development: Key Applications Apr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

See all articles