Streamlit Explanation Column (10): Data Visualization - Detailed Explanation of Chart Drawing (Part 1)


insert image description here

1 Introduction

In the world of data visualization, drawing clear, easy-to-understand graphs is critical. Streamlit is a popular Python library that provides a simple interface and powerful features to help users easily create interactive applications and data visualizations. The Chart elements (chart elements) section provides us with a variety of chart types to display data.

This article provides an in-depth introduction to several important chart elements in Streamlit: st.line_chart, st.area_chart, st.bar_chart, and st.pyplot. By using these elements, you can draw a variety of charts with minimal code, making your data more vivid and easy to understand.

In the next sections, we'll dive into the purpose and sample code of each chart element, and explore how they can be used to represent data in a Streamlit application. Whether you are a data scientist, data engineer, or a hobbyist interested in data visualization, this article will provide you with useful information and hands-on experience.

Let's start exploring these powerful charting elements in Streamlit!

2 st.line_chart: Draw a line chart

In data visualization, a line graph is a common type of chart used to show trends over time or other continuous variables. The st.line_chart method in Streamlit can help us draw a line chart in the simplest way, making the data trend more intuitive and easy to understand.

Let's use an example to demonstrate how to draw a line chart using st.line_chart. First, we need to import Streamlit, Pandas and NumPy libraries, and prepare some sample data:

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

chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=['a', 'b', 'c'])

In the above code, we create a DataFrame with 20 rows and 3 columns, where the data are random numbers generated using NumPy. Each column will correspond to a line on the line graph.

Next, we can use the st.line_chart method to draw a line chart, the code is as follows:

st.line_chart(chart_data)

insert image description here

By running the above code, a line graph will be displayed in the Streamlit application, which shows the trend of the random data.

Using the st.line_chart method is very simple. Just pass the data to be plotted to this method, and the corresponding line graph can be obtained in the Streamlit application. Streamlit will automatically draw a complete line graph according to the changes in the data, and provide some interactive functions, such as zooming and hovering.

This is a very basic example, you can flexibly use the st.line_chart method to plot your own dataset. You can apply it to various scenarios such as time series data, stock trends, and motion trajectories.

3 st.area_chart: draw area chart

In data visualization, an area chart is a commonly used chart type, which is used to show the trend of data changes over time or other continuous variables, and at the same time show the relative size relationship between different data series. The st.area_chart method in Streamlit provides us with a simple way to draw an area chart to display data more intuitively and easily understandable.

Next, let's use an example to demonstrate how to use st.area_chart to draw an area chart. Similarly, we need to import Streamlit, Pandas and NumPy libraries, and prepare some sample data:

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

chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=['a', 'b', 'c'])

In the above code, we create a DataFrame with 20 rows and 3 columns, where the data are random numbers generated using NumPy. Each column will correspond to an area on the area chart.

Next, we can use the st.area_chart method to draw an area chart, the code is as follows:

st.area_chart(chart_data)

insert image description here

By running the above code, an area chart will be displayed in the Streamlit application, which shows the trend of random data, and uses different colored filled areas to represent different data series.

Similar to the st.line_chart method, using the st.area_chart method is also very simple. You only need to pass the data to be drawn to this method, and Streamlit will automatically draw a complete area chart according to the change of the data.

With the area chart, you can observe the changing trend of the data more intuitively, and compare the relative sizes of different data series. This is great for showing data like stock movements, sales trends, temperature changes, etc.

4 st.bar_chart: Draw a histogram

A histogram (Bar Chart) is a common data visualization chart used to show the comparison between the quantities or values ​​of different categories or data groups. In Streamlit, we can use the st.bar_chart method to draw a histogram with intuitive effects to better present and analyze our data.

Now, let's use an example to demonstrate how to use the st.bar_chart method to draw a bar chart. Similarly, we need to import Streamlit, Pandas and NumPy libraries, and prepare some sample data:

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

chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=["a", "b", "c"])

In the above code, we create a DataFrame with 20 rows and 3 columns, where each column represents a column on a histogram.

Next, we can use the st.bar_chart method to draw a histogram, the code is as follows:

st.bar_chart(chart_data)

By running the above code, a histogram will be displayed in the Streamlit application, which shows the comparison between different categories of random data or groups of data. The height of each bar represents the quantity or value for that category or data group.

Using the st.bar_chart method is very simple. Just pass the data to be plotted to this method and get the corresponding histogram in the Streamlit application. Streamlit will automatically draw a complete histogram according to the changes in the data, and provide some interactive functions, such as hovering and clicking.

Histograms are usually used to display classified data, compare data, analyze trends, etc. Through the histogram, we can more intuitively grasp the differences and relationships between the data.

5 st.pyplot: Draw custom charts

Sometimes, we may need to draw some specific types of custom charts to better meet the needs of data visualization. In Streamlit, we can use the st.pyplot method to draw custom charts, such as various chart types provided by Matplotlib.

Let's walk through an example to demonstrate how to use st.pyplot methods to draw custom plots. In order to use Matplotlib to draw charts, we need to import Streamlit, Matplotlib and NumPy libraries, and prepare some sample data:

import streamlit as st
import matplotlib.pyplot as plt
import numpy as np

arr = np.random.normal(1, 1, size=100)
fig, ax = plt.subplots()
ax.hist(arr, bins=20)

In the above code, we use NumPy to generate a set of random normal distribution sample data arr. Then, we used Matplotlib to draw a histogram and set 20 bars as the division interval.

Next, we can use the st.pyplot method to display the custom chart we draw, the code is as follows:

st.pyplot(fig)

insert image description here

Running the above code will display a custom chart in the Streamlit application that shows a histogram of random normal distribution sample data. We can customize and adjust as needed to meet specific needs.

It should be noted that with the update of Streamlit, starting from December 1, 2020, we will no longer support the usage of not passing in parameters in the st.pyplot method, because this will use the global graphics object of Matplotlib, such Usage is not thread safe. So, always pass graphics objects as in the example above.

In addition, Matplotlib supports a variety of backend (backend) types. If you encounter errors when using Matplotlib with Streamlit, try setting the backend to "TkAgg".

Through the st.pyplot method, we can easily display various custom charts in the Streamlit application to meet the needs of different data visualizations.

6 Epilogue

In this blog post, we introduced several commonly used data visualization methods in the Streamlit library, including drawing line charts, area charts, histograms and custom charts.

Through the st.line_chart method, we can visualize the data as a line graph to visually show the trend and change of the data.

Using the st.area_chart method, we can create area charts that better represent the distribution of data across categories or time periods.

The st.bar_chart method can be used to draw a bar chart to clearly compare the differences between different categories or groups of data.

For some specific needs or complex chart types, we can use the st.pyplot method to display the custom charts drawn by Matplotlib in the Streamlit application.

Through these data visualization methods, we can better understand and communicate data, which supports more accurate analysis and decision-making.

In the next blog post, we will introduce some other common data visualization methods, so stay tuned!

Hope this article provided you with valuable information. If you have any questions or need further information, please feel free to ask. Good luck with your data visualization with Streamlit!

insert image description here

Guess you like

Origin blog.csdn.net/weixin_46043195/article/details/132285177