How to draw stacked charts and pie charts using Matplotlib
Matplotlib is a Python 2D plotting library that can generate publication-quality graphics in a variety of hardcopy formats and interactive environments on a variety of platforms.
In the last Matplotlib data visualization tutorial, we will introducehow to createbar charts, histograms and scatter plots. Today we bring you two other types of charts, stacked charts and pie charts. Because these two diagrams are very similar, they are introduced together.
Stacked Chart
Stacked chart is used to show the relationship of "part to whole" over time. A stacked chart is basically like a pie chart, only it changes over time.
Let's consider a situation where we have 24 hours in a day and we want to see how we spend our time. We divide our activities into: sleeping, eating, working and playing.
We assume we want to track it over a period of 5 days, so our initial data will look like this:
import matplotlib.pyplot as plt days = [1,2,3,4,5] sleeping = [7,8,6,11,7] eating = [2,3,4,3,2] working = [7,8,7,2,2] playing = [8,5,7,8,13]
Therefore, our x-axis will include the day variable, which is 1, 2, 3, 4 and 5. The individual components of the date are then kept in their respective activities. Draw them like this:
plt.stackplot(days, sleeping,eating,working,playing, colors=['m','c','r','k']) plt.xlabel('x') plt.ylabel('y') plt.title('Interesting Graph\nCheck it out') plt.show()
Here we can see, at least in color, how we spend our time. The problem is, without looking back at the code, we don't know what color is what. The next problem is that with polygons we can't actually add "labels" to the data. So anywhere that's more than just lines, with a fill or a stacked diagram like this, we can't inherently mark out specific parts. This shouldn't stop programmers. We can fix this:
import matplotlib.pyplot as plt days = [1,2,3,4,5] sleeping = [7,8,6,11,7] eating = [2,3,4,3,2] working = [7,8,7,2,2] playing = [8,5,7,8,13] plt.plot([],[],color='m', label='Sleeping', linewidth=5) plt.plot([],[],color='c', label='Eating', linewidth=5) plt.plot([],[],color='r', label='Working', linewidth=5) plt.plot([],[],color='k', label='Playing', linewidth=5) plt.stackplot(days, sleeping,eating,working,playing, colors=['m','c','r','k']) plt.xlabel('x') plt.ylabel('y') plt.title('Interesting Graph\nCheck it out') plt.legend() plt.show()
What we do here is draw some empty rows, give them the same color as our stacked plot, and the correct labels. We also give them a line width of 5 to make the lines appear wider in the legend. Now we can easily see how we spend our time.
Pie Chart
Pie charts are much like stacked charts, except they are located at a certain point in time. Typically, pie charts are used to show how a part contributes to a whole, usually in %. Fortunately, Matplotlib takes care of the slice size and everything, we just need to provide the numerical value.
import matplotlib.pyplot as plt slices = [7,2,2,13] activities = ['sleeping','eating','working','playing'] cols = ['c','m','r','b'] plt.pie(slices, labels=activities, colors=cols, startangle=90, shadow= True, explode=(0,0.1,0,0), autopct='%1.1f%%') plt.title('Interesting Graph\nCheck it out') plt.show()
In plt.pie, we need to specify the "slice", which is the relative size of each part. We then specify a list of colors for the corresponding slices. Next, we can choose to specify the "start angle" of the graphic. This allows you to start drawing anywhere. In our example, we chose a 90-degree angle for the pie chart, which means the first segment is a vertical line. Next, we have the option to add a character-sized shadow to the drawing, and then we can even use explode to pull out a slice.
We have a total of four slices, so for explode, if we don't want to pull out any slices, we pass in 0,0,0,0. If we want to pull the first slice, we pass in 0.1,0,0,0.
Finally, we use autopct to choose to place the percentage on the chart.
The above is the detailed content of How to draw stacked charts and pie charts using Matplotlib. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.
