How to draw a stacked column chart using ECharts in Python
In the field of data visualization, stacked histograms are a common visualization method. It draws multiple data series into a bar. Each bar is composed of multiple sub-items. Each sub-item corresponds to a data series and is displayed in the same coordinate system. This kind of chart can be used to compare the total size of different categories or data series, the proportion of components of each category or data series, etc. In Python, we can use the ECharts library to draw stacked histograms, and the library is richly customizable and interactive.
1. Install and import the ECharts library
Before using the ECharts library, we need to install it first. It can be installed through the pip command:
pip install pyecharts
After the installation is completed, we need to import the required components in the Python script, for example:
from pyecharts import options as opts from pyecharts.charts import Bar from pyecharts.faker import Faker
2. Draw a stacked histogram
Next, let's look at an example in which we will use the ECharts library to draw a stacked column chart to show sales for each month, where each column represents a month's sales, and each column is represented by Sales composition of different product categories.
- Prepare data
First, we need to prepare the data. In this example, we randomly generated sales data for 12 months, and each month included sales of 3 product categories. The code is as follows:
import random # 随机生成12个月份的销售额数据 months = [str(i) + "月" for i in range(1, 13)] type1_sales = [random.randint(100, 1000) for _ in range(12)] type2_sales = [random.randint(100, 1000) for _ in range(12)] type3_sales = [random.randint(100, 1000) for _ in range(12)]
- Draw the chart
Next, we add the data to the chart and customize it. The code is as follows:
# 实例化柱状图 bar = ( Bar() # 添加X轴数据 .add_xaxis(months) # 添加Y轴数据,并使用整数值格式化标签 .add_yaxis("类别1", type1_sales, stack="stack1", label_opts=opts.LabelOpts(formatter="{value}元")) .add_yaxis("类别2", type2_sales, stack="stack1", label_opts=opts.LabelOpts(formatter="{value}元")) .add_yaxis("类别3", type3_sales, stack="stack1", label_opts=opts.LabelOpts(formatter="{value}元")) # 设置全局参数 .set_global_opts( # 设置标题 title_opts=opts.TitleOpts(title="堆叠柱状图"), # 设置X轴标签旋转角度 xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-15)), # 设置Y轴的名称和最大值 yaxis_opts=opts.AxisOpts(name="销售额", max_=3000), # 设置数据标签 series_opts=opts.SeriesOpts( itemstyle_opts=opts.ItemStyleOpts(border_color="black", border_width=0), label_opts=opts.LabelOpts(is_show=True, position="inside", color="white") ) ) )
In the above code, we instantiate a histogram and use add_xaxis() to add the X-axis data to the chart. Next, we use add_yaxis() to add three types of sales data to the chart. Since we need to stack three types of sales together, we set them all to stack1. At the same time, we use label_opts to set the formatting method of the label. Finally, we use set_global_opts() to set the global parameters of the chart, including the title, X-axis label rotation angle, Y-axis name and maximum value, and data label settings.
- Visualize and save the results
Finally, we use render() to visualize the results and display the results in Jupyter Notebook using render_notebook() or render(' filename.html') saves the results as an HTML file. The code is as follows:
# 在Jupyter Notebook中显示图表 bar.render_notebook() # 将图表保存为HTML文件 bar.render("bar_chart.html")
After running the above code, we will get a clear stacked column chart, which shows the sales of each month and can reflect the proportion of sales of different product categories. than the situation.
3. Summary
This article introduces how to use the Bar component in the ECharts library to draw a stacked column chart, and uses specific code examples to show how to prepare data and how to add data to the chart. And how to customize and save charts. Of course, in actual operation, more detailed settings and adjustments to the parameters of specific components may be required to meet different visualization needs. But overall, ECharts provides Python users with a powerful and easy-to-use data visualization tool that helps to better present the results obtained during the data analysis process.
The above is the detailed content of How to draw a stacked column chart using ECharts in Python. For more information, please follow other related articles on the PHP Chinese website!

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.

Pythondoesnothavebuilt-inarrays;usethearraymoduleformemory-efficienthomogeneousdatastorage,whilelistsareversatileformixeddatatypes.Arraysareefficientforlargedatasetsofthesametype,whereaslistsofferflexibilityandareeasiertouseformixedorsmallerdatasets.

ThemostcommonlyusedmoduleforcreatingarraysinPythonisnumpy.1)Numpyprovidesefficienttoolsforarrayoperations,idealfornumericaldata.2)Arrayscanbecreatedusingnp.array()for1Dand2Dstructures.3)Numpyexcelsinelement-wiseoperationsandcomplexcalculationslikemea

ToappendelementstoaPythonlist,usetheappend()methodforsingleelements,extend()formultipleelements,andinsert()forspecificpositions.1)Useappend()foraddingoneelementattheend.2)Useextend()toaddmultipleelementsefficiently.3)Useinsert()toaddanelementataspeci

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

In the fields of finance, scientific research, medical care and AI, it is crucial to efficiently store and process numerical data. 1) In finance, using memory mapped files and NumPy libraries can significantly improve data processing speed. 2) In the field of scientific research, HDF5 files are optimized for data storage and retrieval. 3) In medical care, database optimization technologies such as indexing and partitioning improve data query performance. 4) In AI, data sharding and distributed training accelerate model training. System performance and scalability can be significantly improved by choosing the right tools and technologies and weighing trade-offs between storage and processing speeds.


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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
