preface
We all know about matplotlib, a visualization tool on Python, but it’s static. Then I discovered the PyEcharts module, which is extremely useful, with a wide variety of visualization types, and it was developed based on Echarts.
Echarts is a baidu open source data visualization JS library, with good interaction, exquisite chart design, has been recognized by many developers. Python, on the other hand, is great for data processing. When data analysis meets data visualization, Pyecharts is born.
Here’s a quick guide to pyEcharts and how to use it:
✨ features
- Simple API design, silky smooth use, support chain call
- It contains over 30 common charts, and you can find everything
- Support mainstream Notebook environment, Jupyter Notebook and JupyterLab
- Easy to integrate into Flask, Django, and other mainstream Web frameworks
- Highly flexible configuration items can be easily matched to create beautiful charts
- Detailed documentation and examples to help developers get started faster
- Up to 400+ maps provide strong support for geographic data visualization
✨ installation
1pip install pyecharts
Copy the code
Note: There are two versions of Pyecharts, v0.5.X and v1.0.x are completely incompatible, and v0.5.X is not maintained by the author, please use V1.0.x
Bar: Bar chart/Bar chart
The module corresponding to the Bar chart is Bar. In addition, you can set global configuration and series configuration items. Configuration items are based on Options
Sample code:
1# coding: utf-8
2from example.commons import Faker
3from pyecharts import options as opts
4from pyecharts.charts import Bar
5
6def bar_base():
7
8 bar = Bar(init_opts=opts.InitOpts(page_title="The bar page")) Set the HTML page title
9 # bar. Add_xaxis ([" shirt "and" sweater ", "snow spins unlined upper garment", "pants", "high heels", "socks"]) # set the parameters of the x axis
10
11 bar.add_xaxis(Faker.choose())
12 bar.add_yaxis("A", Faker.values())
13 bar.add_yaxis("B", Faker.values())
14
15 Set the global configuration item, optional
16 bar.set_global_opts(opts.TitleOpts(title="Main title", subtitle="Subtitle"))
17 # render generates a local HTML file, default render
18 bar.render("bar.html") You can also specify the file name
19
20if __name__ == "__main__":
21 bar_base()
Copy the code
Running the code generates a “bar.html” file in the current directory, which we open in a browser. The renderings are as follows:
Generated page support – click to cancel showing a Series
In addition to the above methods, all pyecharts methods support chained calls!
Flip the XY axis
The code is as follows:
1 def bar_reversal_axis(a) -> Bar:
2
3 All pyecharts methods support chained calls.
4 c = (
5 Bar(init_opts=opts.InitOpts(page_title="The bar page"))
6 .add_xaxis(Faker.choose())
7 .add_yaxis("Merchants A", Faker.values())
8 .add_yaxis(Merchants "B", Faker.values())
9 .reversal_axis()
10 .set_global_opts(toolbox_opts=opts.ToolboxOpts()) Set the toolbox configuration items
11 .set_series_opts(label_opts=opts.LabelOpts(position="right")) # Series configuration items
12 .set_global_opts(title_opts=opts.TitleOpts(title="Bar-flip XY axis")) # global configuration item
13 )
14 return c
15
16
17if __name__ == "__main__":
18 bar_reversal_axis().render("bar.html")
Copy the code
The renderings are as follows:
Partial stack data
Stack values configured in the same series on the same category axis can be stacked
For example, stack A, B:
1 def bar_stack1(a) -> Bar:
2 c = (
3 Bar()
4 .add_xaxis(Faker.choose())
5
6 # Data stack, same emSP configuration on the same category axis; stack Values can be stacked.
7 # stack: Optional[str] = None,
8 .add_yaxis("A", Faker.values(), stack="stack1")
9 .add_yaxis("B", Faker.values(), stack="stack1")
10 .add_yaxis("C", Faker.values())
11 .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
12 .set_global_opts(title_opts=opts.TitleOpts(title="Bar- Stack data (part)"))
13 )
14 return c
Copy the code
Area scaling configuration item
1 def bar_datazoom_slider(a) -> Bar:
2 c = (
3 Bar(init_opts=opts.InitOpts(page_title="The bar page"))
4 .add_xaxis(Faker.days_attrs)
5 .add_yaxis("Merchants A", Faker.days_values)
6 .set_global_opts(
7 title_opts=opts.TitleOpts(title="Bar-datazoom (slider-level)"),
8 datazoom_opts=[opts.DataZoomOpts(type_="slider", a)]9 )
10 )
11 return c
Copy the code
The renderings are as follows:
DataZoomOpts class, we can click to view the source code: DataZoomOpts
The main meanings of parameters are as follows:
1 type_: str = "slider".# Component type, optional "slider", "inside"
2 # Whether to update series views in real time when dragging. If set to false, updates are only made when the drag ends.
3 is_realtime: bool = True.4
5 Is the layout horizontal or vertical? Optional values are: 'horizontal', 'vertical'
6 orient: str = "horizontal".Copy the code
Now that we know what the parameters mean we can try it out
For example, if we want to change the region scale layout to vertical and define Orient as vertical, the code is not displayed, you can try it yourself!
The renderings are as follows:
HeatMap: HeatMap
The thermal map is mainly used to represent the size of the value through color and must be used with the visualMap component. Two category axes must be used in a rectangular coordinate system.
The method function used for the thermogram is add_yaxis. The following is the usage description of the function:
i 1def add_yaxis(
2 # Series name for tooltip display, legend filter.
3 series_name: str,
4
5 # Y coordinate data
6 yaxis_data: Sequence,
7
8 # Series data items
9 value: Sequence,
10
11 # check whether legend is selected
12 is_selected: bool = True.13
14 # use the X-axis index, which is useful when there are multiple x-axes in a single chart instance.
15 xaxis_index: Optional[Numeric] = None.16
17 # use the Y-axis index, which is useful when there are multiple y-axes in a single chart instance.
18 yaxis_index: Optional[Numeric] = None.19
20 # tag configuration item, see 'series_options.LabelOpts'
21 label_opts: Union[opts.LabelOpts, dict] = opts.LabelOpts(),
22
23 # mark the point configuration item, see 'series_options.MarkPointOpts'
24 markpoint_opts: Union[opts.MarkPointOpts, dict, None] = None.25
26 # mark line configuration items, see 'series_options.MarkLineOpts'
27 markline_opts: Union[opts.MarkLineOpts, dict, None] = None.28
29 # Prompt box component configuration item, see 'series_options.TooltipOpts'
30 tooltip_opts: Union[opts.TooltipOpts, dict, None] = None.31
32 For the meta-style configuration item, see 'series_options.ItemStyleOpts'
33 itemstyle_opts: Union[opts.ItemStyleOpts, dict, None] = None.34
35
Copy the code
Where series_name, yaxis_data, and value are mandatory parameters, the following is an example code:
import random
from example.commons import Faker
from pyecharts import options as opts
from pyecharts.charts import HeatMap
def heatmap_base(a) -> HeatMap:
value = [[i, j, random.randint(0.50)] for i in range(24) for j in range(7)]
c = (
HeatMap()
.add_xaxis(Faker.clock)
.add_yaxis("series", Faker.week, value)
.set_global_opts(title_opts=opts.TitleOpts(title="HeatMap- Basic Examples"),
visualmap_opts=opts.VisualMapOpts(), )
)
return c
if __name__ == "__main__":
heatmap_base().render("heatMap.html")
Copy the code
The renderings are as follows:
WordCloud: a WordCloud
The method function of the word cloud map is add, which is used as follows:
1 def add(
2# Series name for tooltip display, legend filter.3 series_name: str,
4
5# series data item, [(word1, count1).(word2, count2)]
6 data_pair: Sequence,
7
8# word cloud outline, there are'circle'.'cardioid'.'diamond'.'triangle-forward'.'triangle'.'pentagon'.'star'optional9 shape: str = "circle".10
11# Word spacing12 word_gap: Numeric = 20.13
14# Word font size range15 word_size_range=None,
16
17# Rotate the word Angle18 rotate_step: Numeric = 45.19
20# Prompt box component configuration item, see 'series_options.TooltipOpts'21 tooltip_opts: Union[opts.TooltipOpts, dict, None] = None,
22
23
Copy the code
Series_name, data_pair, and shape are mandatory parameters. The following is an example code:
# coding: utf-8
import random
from pyecharts.charts import WordCloud
from pyecharts import options as opts
words = [
("Rocket", 10000),
("Curry the Warrior.", 8888),
("I knew how to use it before you wrote this tutorial.", 6181),
("Harden", 6386),
("Lavine, Golden State.", 5055),
("Durant", 6467),
(Stamp "eye", 2244),
("NBA", 1868),
("Playoffs", 1484),
("Teacher appointment", 1112),
("Lillard", 865),
("Double card double standby", 847),
("Alphabet Song MVP.", 5582),
("Kawaii", 555),
("Toronto", 550),
("The emperor", 462),
("Simmons doesn't shoot 3s.", 366),
("JB", 360),
("Cole garbage.", 282),
(Green's Formula, 273),
("Owen", 2650),
]
def wordcloud_base() -> WordCloud:
c = (
WordCloud()
.add("", words, word_size_range=[20, 50], shape="diamond", word_gap=10)
.set_global_opts(title_opts=opts.TitleOpts(title="WordCloud-shape-diamond")))return c
if __name__ == "__main__":
wordcloud_base().render("wordCloud.html")
Copy the code
The renderings are as follows:
Save as a picture
Pyecharts also provides a way to save graphics as images
Snapshot_selenium needs to be installed and the browser driver save path cheromdriver.exe needs to be added to the environment variable
1pip install snapshot_selenium
Copy the code
Example code is as follows:
1 # coding: utf-8
2 import random
3
4 from pyecharts.charts import WordCloud
5 from pyecharts import options as opts
6 from snapshot_selenium import snapshot as driver
7 from pyecharts.render import make_snapshot
8
9 words = [
10 ("Rocket".10000),
11 ("Curry the Warrior.".8888),
12 ("I knew how to use it before you wrote this tutorial.".6181),
13 ("Harden".6386),
14 ("Lavine, Golden State.".5055),
15 ("Durant".6467),
16 (Stamp "eye".2244),
17 ("NBA".1868),
18 ("Playoffs".1484),
19 ("Teacher appointment".1112),
20 ("Lillard".865),
21 ("Double card double standby".847),
22 ("Alphabet Song MVP.".5582),
23 ("Kawaii".555),
24 ("Toronto".550),
25 ("The emperor".462),
26 ("Simmons doesn't shoot 3s.".366),
27 ("JB".360),
28 ("Cole garbage.".282),
29 (Green's Formula.273),
30 ("Owen".2650),
31]
32
33
34 def wordcloud_base(a) -> WordCloud:
35 c = (
36 WordCloud()
37 .add("", words, word_size_range=[20.50], shape="diamond", word_gap=10)
38 .set_global_opts(title_opts=opts.TitleOpts(title="WordCloud-shape-diamond"))
39 )
40 return c
41
42
43 if __name__ == "__main__":
44 make_snapshot(driver, wordcloud_base().render(), "wordcloud.png")
45 # wordcloud_base().render("wordCloud.html")
Copy the code
Finally, a wordcloud.png image is generated in the current directory
conclusion
1. Import related packages according to the graphics you want to make
2. Perform basic chart Settings and create a chart object
3. Understand the meaning and usage of parameters in the function below the chart object
4. Configuration items are mainly configured in Options, including global configuration items and series configuration items. You need to understand the meanings and usage of the objects below configuration items
5. Use the render() method to save the chart
Pyecharts also has many interesting 3D charts and maps. Due to space constraints, the next part will continue to introduce the gameplay of the map system.
Recommended reading
Python crawlers: An introduction to JS reverse
Create your wechat friends’ avatar wall with one click in Python
The combination of Pyecharts visualization and wechat
Python Data Visualization artifact – Pyecharts quick start