PyEcharts in-depth learning

1. Overview of pyecharts

1.1 import chart type

Like the import method of other libraries, you must first import the required chart type at the beginning of the file before drawing.

from pyecharts.charts import Bar

Bar type is the English name of histogram / bar chart in pyEcharts. There are many commonly used chart types in py charts, such as Pie, wordcloud, Scatter, and so on.

After import ing the icon type we need, declare the chart like an instantiated class in object-oriented:

bar = Bar()

1.2 adding data

Once the chart is instantiated, you can add data to the chart. The methods of adding data for different types of charts in pyechards are different, but the basic principle is similar. Here, take Bar chart, i.e. Bar chart, as an example to introduce the method of adding data.

Examples are as follows:

bar.add_xaxis(["Shirts", "Sweaters", "Ties", "Pants", "Windbreaker", "High-heels", "Socks"])
bar.add_yaxis("Merchant-A", [114, 55, 27, 101, 125, 27, 105])
bar.add_yaxis("Merchant-B", [57, 134, 137, 129, 145, 60, 49])

The above code is to add six clothing types to the x-axis of bar, and add two groups of sales data of merchant A and merchant B to the y-axis respectively. pyEcharts will automatically draw A histogram of two lines in each group.

1.3 setting chart style

With the data, we can set the icon style we need and add some additional information.

For example, flip the x-axis and y-axis:

bar.reversal_axis()

This setting type belongs to Bar chart's own type.

Set the position of the label to display to the right:

bar.set_series_opts(label_opts=opts.LabelOpts(position="right"))

This setting type belongs to the Series Option. Series configuration items can also set text type, element type, and so on.

Set the title to bar testpicture

bar.set_global_opts(title_opts=opts.TitleOpts(title="Bar-TestPicture"))

The title setting belongs to the Global Option. Refer to the following figure for the specific part names:

1.4 output chart

Pyecarts can be output in a variety of formats, such as embedded Web interface output in html format, embedded Jupyter output, or PNG format image output in the form of file.

make_snapshot(snapshot, bar_chart().render(), "StudentAnswer/student_answer.png")

1.5 chain call

bar = (
      Bar()
      .add_xaxis(["Shirts", "Sweaters", "Ties", "Pants", "Windbreaker", "High-heels", "Socks"])
      .add_yaxis("Merchant-A", [114, 55, 27, 101, 125, 27, 105])
      .add_yaxis("Merchant-B", [57, 134, 137, 129, 145, 60, 49])
)

1.6 examples

from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.render import make_snapshot
 
from snapshot_phantomjs import snapshot
 
def bar_chart() -> Bar:
 
    # ********* Begin *********#    
    bar = Bar()
    bar.add_xaxis(["Shirts", "Sweaters", "Ties", "Pants", "Windbreaker", "High-heels", "Socks"])
    bar.add_yaxis("Merchant-A", [114, 55, 27, 101, 125, 27, 105])
    bar.add_yaxis("Merchant-B", [57, 134, 137, 129, 145, 60, 49])
    bar.reversal_axis()
    bar.set_series_opts(label_opts=opts.LabelOpts(position="right"))
    bar.set_global_opts(title_opts=opts.TitleOpts(title="Bar-TestPicture"))
    # ********** End **********#
    return bar
 
make_snapshot(snapshot, bar_chart().render(), "StudentAnswer/student_answer.png")

2. Histogram / bar chart of pyecharts rectangular coordinate system chart

2.1 import required packages

The import statement is as follows:

from pyecharts.charts import Bar

To facilitate data construction, we also imported the virtual data package provided by PyEcharts, as shown below:

from pyecharts.faker import Faker

In addition, the theme type in the global variable is imported to assist in setting the theme type.

from pyecharts.globals import ThemeType

For specific topics, see: Official documents

2.2 construction data

Through the virtual data packet Faker provided by PyEcharts, we can construct data for x-axis and y-axis respectively with the following statements:

data_x = Faker.choose()
data_y_1 = Faker.values()
data_y_2 = Faker.values()

Among them, the choose method in the Faker package will randomly select a set of attributes, while the values method will generate random data values.

2.3 general method of rectangular coordinate system chart

Rectangular coordinate system charts are inherited from RectChart and have the following methods:

Add X-axis data:

def add_xaxis(
    # X-axis data item
    xaxis_data: Sequence
)

Extended X/Y axis:

def extend_axis(
    # Extended X-axis data item
    xaxis_data: Sequence = None,
    # Extended X-axis configuration item, refer to ` global_options.AxisOpts`
    xaxis: Union[opts.AxisOpts, dict, None] = None,
    # New Y-axis configuration item, refer to ` global_options.AxisOpts`
    yaxis: Union[opts.AxisOpts, dict, None] = None,
)

Flip XY axis data:

def reversal_axis():

Add dataset component:

def add_dataset(
    # raw data. Generally speaking, the original data represents a two-dimensional table.
    source: types.Union[types.Sequence, types.JSFunc] = None,
    # Use dimensions to define the information of each dimension of series.data or dataset.source.
    dimensions: types.Optional[types.Sequence] = None,
    # Whether the first row / column of dataset.source is dimension name information. Optional values:
    # null/undefine (corresponding to the None value of Python): default, automatic detection.
    # true: the first row / column is dimension name information.
    # false: the first row / column starts directly with data.
    source_header: types.Optional[bool] = None,

2.4 Y-axis configuration item of histogram

The Y-axis configuration interface of the histogram is as follows:

class Bar(
    # Initialize configuration items, refer to ` global_options.InitOpts`
    init_opts: opts.InitOpts = opts.InitOpts()
)
func pyecharts.charts.Bar.add_yaxis
def add_yaxis(
    # Series name, used for displaying tooltip and legend filtering of legend.
    series_name: str,
    # Series data
    y_axis: Sequence[Numeric, opts.BarItem, dict],
    # Check legend
    is_selected: bool = True,
    # The x-axis index used is useful when there are multiple X-axes in a single chart instance.
    xaxis_index: Optional[Numeric] = None,
    # The y-axis index used is useful when there are multiple Y-axes in a single chart instance.
    yaxis_index: Optional[Numeric] = None,
    # Whether to enable linkage highlighting when legend hover is enabled
    is_legend_hover_link: bool = True,
    # Series label colors
    color: Optional[str] = None,
    # Whether to display the background color of the column bar. Configure the background style through the backgroundStyle.
    is_show_background: bool = False,
    # The background style of each column bar. It is valid only when showBackground needs to be set to true.
    background_style: types.Union[types.BarBackground, dict, None] = None,
    # Data stacking: the series on the same category axis can be stacked with the same stack value.
    stack: Optional[str] = None,
    # The width of the column bar is adaptive when not set.
    # It can be an absolute value such as 40 or a percentage such as' 60% '. The percentage is based on the automatically calculated width of each category.
    # On the same coordinate system, this attribute will be shared by multiple 'bar' series. This property should be set on the last 'bar' Series in this coordinate system to take effect, and it takes effect on all 'bar' Series in this coordinate system.
    bar_width: types.Union[types.Numeric, str] = None,
    # The maximum width of the column bar. Higher priority than barWidth.
    bar_max_width: types.Union[types.Numeric, str] = None,
    # The minimum width of the column bar. In a rectangular coordinate system, the default value is 1. Otherwise, the default value is null. Higher priority than barWidth.
    bar_min_width: types.Union[types.Numeric, str] = None,
    # The minimum height of the column bar, which can be used to prevent the value of a data item from being too small to affect the interaction.
    bar_min_height: types.Numeric = 0,
    # The distance between columns in the same series is 20% of the category spacing by default, and a fixed value can be set
    category_gap: Union[Numeric, str] = "20%",
    # The distance between columns of different series is a percentage (e.g. '30%', representing 30% of the column width).
    # If you want two series of columns to overlap, you can set gap to '- 100%'. This is useful when using columns as a background.
    gap: Optional[str] = "30%",
    # Whether to enable large amount of data optimization can be enabled when there are too many data graphics and there is a jam.
    # When enabled, optimize the rendering when the amount of data is greater than the specified threshold in conjunction with largeThreshold.
    # Disadvantages: after optimization, you cannot customize the style of a single data item.
    is_large: bool = False,
    # Turns on the threshold for paint optimization.
    large_threshold: types.Numeric = 400,
    # Use dimensions to define the information of each dimension of series.data or dataset.source.
    # Note: if dataset is used, the dimension name can be given in the first row / column of dataset.source.
    # So you don't have to specify the dimension here.
    # However, if dimensions are specified here, ECharts will no longer automatically obtain dimension information from the first row / column of dataset.source.
    dimensions: types.Union[types.Sequence, None] = None,
    # When using a dataset, seriesLayoutBy specifies whether the row or column in the dataset corresponds to the series, that is, whether the series is "arranged" to the row or column of the dataset. Available values:
    # 'column': by default, the column of the dataset corresponds to a series, so each column in the dataset is a dimension.
    # 'row': the row of the dataset corresponds to the series, so each row in the dataset is a dimension.
    series_layout_by: str = "column",
    # If series.data is not specified and the dataset exists, the dataset will be used.
    # datasetIndex specifies which dataset this series uses.
    dataset_index: types.Numeric = 0,
    # Whether to crop the drawing beyond the coordinate system. Histogram: cut out all parts beyond the coordinate system, but still keep the width of the column
    is_clip: bool = True,
    # The zlevel value of all graphs of the histogram.
    z_level: types.Numeric = 0,
    # z values for all graphs of the histogram component. Controls the sequence of drawings.
    # A graph with a small z value will be overwritten by a graph with a large z value.
    # z has lower priority than zlevel, and no new Canvas will be created.
    z: types.Numeric = 2,
    # Label configuration item, refer to ` series_options.LabelOpts`
    label_opts: Union[opts.LabelOpts, dict] = opts.LabelOpts(),
    # Marker point configuration item, refer to ` series_options.MarkPointOpts`
    markpoint_opts: Union[opts.MarkPointOpts, dict, None] = None,
    # Marker line configuration item, refer to ` series_options.MarkLineOpts`
    markline_opts: Union[opts.MarkLineOpts, dict, None] = None,
    # Prompt box component configuration item, refer to ` series_options.TooltipOpts`
    tooltip_opts: Union[opts.TooltipOpts, dict, None] = None,
    # Element style configuration item, refer to ` series_options.ItemStyleOpts`
    itemstyle_opts: Union[opts.ItemStyleOpts, dict, None] = None,
    # You can define which dimension of data is encoded into what.
    encode: types.Union[types.JSFunc, dict, None] = None,
)

2.5 initialization configuration item

class InitOpts(
    # Chart canvas width, css length unit.
    width: str = "900px",
    # Chart canvas height, css length unit.
    height: str = "500px",
    # Chart ID, the unique ID of the chart, which is used to distinguish between multiple charts and tables.
    chart_id: Optional[str] = None,
    # Rendering style, optional "canvas", "svg"
    # # Refer to the chapter "global variables"
    renderer: str = RenderType.CANVAS,
    # Page title
    page_title: str = "Awesome-pyecharts",
    # Chart theme
    theme: str = "white",
    # Chart background color
    bg_color: Optional[str] = None,
)

2.6 examples

  • Use the MACARONS topic in the global variable

  • The X-axis data is set to data_x

  • Add two sets of Y-axis data. The name of the first group of series is set to "merchant A", and the data is data_ Y_ one

  • The name of the second group of series is set to "merchant B", and the data is data_y_2. Check whether the legend is set to No

  • Set the Bar chart title to Bar basic example

  • Add a subtitle to the histogram and name it "I also configured it through dict"

from PreTest import *
from pyecharts import options as opts
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot
 
from pyecharts.charts import Bar
 
from pyecharts.faker import Faker
from pyecharts.globals import ThemeType
 
data_x = Faker.choose()
data_y_1 = Faker.values()
data_y_2 = Faker.values()
 
 
def bar_chart() -> Bar:
    # ********* Begin *********#  
    c = (
            Bar(init_opts=opts.InitOpts(theme=ThemeType.MACARONS))
            .add_xaxis(data_x)
            .add_yaxis("business A",data_y_1)
            .add_yaxis("business B",data_y_2,is_selected=False)
            .set_global_opts(
                title_opts=opts.TitleOpts(
                    title="Bar-Basic example",
                    subtitle="I passed, too dict For configuration"),
                    )
    )
    # ********** End **********#
    return c
 
make_snapshot(snapshot, bar_chart().render("Result/render.html"), 'StudentAnswer/student_answer.png') # Output picture
make_snapshot(snapshot, bar_base(data_x, data_y_1, data_y_2).render(), "StandardAnswer/task1/standard_answer_1.png")

2.7 data item interface

class BarItem(
    # Data item name.
    name: Optional[str] = None,
    # The value of a single data item.
    value: Optional[Numeric] = None,
    # For style settings of single column text, refer to ` series_options.LabelOpts`. 
    label_opts: Union[LabelOpts, dict, None] = None,
    # Element style configuration item, refer to ` series_options.ItemStyleOpts`
    itemstyle_opts: Union[ItemStyleOpts, dict, None] = None,
    # Prompt box component configuration item, refer to ` series_options.TooltipOpts`
    tooltip_opts: Union[TooltipOpts, dict, None] = None,
)

2.8 coordinate axis configuration items

In addition to using the coordinate axis configuration item of the chart itself, you can also use the coordinate axis configuration item in the global configuration item to set the coordinate axis style:

class AxisOpts(
    # Axis type. Optional:
    # 'value': value axis, applicable to continuous data.
    # 'category': category axis, which is applicable to discrete category data. Category data must be set through data for this type.
    # 'time ': time axis, which is applicable to continuous time series data. Compared with the numerical axis, the time axis has time formatting and is different in scale calculation,
    # For example, the scale of month, week, day or hour range will be used according to the span range.
    # 'log' pairs the number axis. Applies to logarithmic data.
    type_: Optional[str] = None,
    # Axis name.
    name: Optional[str] = None,
    # Whether the x-axis is displayed.
    is_show: bool = True,
    # Valid only in the value axis (type: 'value').
    # Whether it is a scale away from the 0 value. When set to true, the coordinate scale does not force zero scale. It is useful in the scatter diagram of double numerical axis.
    # The configuration item is invalid after setting min and max.
    is_scale: bool = False,
    # Whether to reverse the coordinate axis.
    is_inverse: bool = False,
    # The axis name displays the location. Optional:
    # 'Start ',' middle 'or' center','end '
    name_location: str = "end",
    # The distance between the axis name and the axis.
    name_gap: Numeric = 15,
    # Axis name, rotation, angle value.
    name_rotate: Optional[Numeric] = None,
    # Forces the axis division interval to be set.
    # Because splitNumber is an estimated value, the actual scale calculated according to the policy may not achieve the desired effect,
    # At this time, interval can be used in conjunction with min and max to forcibly set the scale division, which is generally not recommended.
    # Cannot be used in category axis. The timestamp needs to be passed in the time axis (type: 'time'), and the index value needs to be passed in the counter axis (type: 'log').
    interval: Optional[Numeric] = None,
    # The index of the grid where the x-axis is located. It is located on the first grid by default.
    grid_index: Numeric = 0,
    # Position of the x-axis. Optional:
    # 'top', 'bottom'
    # The first X-axis in the default grid is below the grid ('bottom '), and the second x-axis is placed on the other side according to the position of the first x-axis.
    position: Optional[str] = None,
    # The offset of the Y axis from the default position is useful when there are multiple Y axes on the same position.
    offset: Numeric = 0,
    # For the number of segments of the coordinate axis, it should be noted that the number of segments is only an estimated value. On this basis, the number of segments actually displayed will be adjusted according to the readability of the scale display of the coordinate axis after segmentation. 
    # The default value is 5
    split_number: Numeric = 5,
    # The setting and performance of category axis and non category axis are different.
    # The boundaryGap in the category axis can be configured as true and false. The default is true. At this time, the scale is only used as a separator,
    # Both labels and data points will be in the middle of the band between the two scales.
    # Non category axis, including time, value and logarithm axis. boundaryGap is an array of two values, representing the extension range of the minimum and maximum values of the data respectively
    # You can directly set the value or relative percentage, which is invalid after setting min and max. Example: boundarygap: ['20% ','20%']
    boundary_gap: Union[str, bool, None] = None,
    # Axis scale min.
    # It can be set to the special value 'dataMin'. At this time, the minimum value of data on this axis is taken as the minimum scale.
    # When not set, the minimum value will be calculated automatically to ensure the uniform distribution of coordinate axis scale.
    # In the category axis, it can also be set as the ordinal number of the category (for example, in the category axis data: ['class A', 'class B', 'Class C'], the ordinal number 2 represents' Class C '.
    # It can also be set to a negative number, such as - 3).
    min_: Union[Numeric, str, None] = None,
    # Axis scale maximum.
    # It can be set to the special value 'dataMax'. At this time, the maximum value of data on this axis is taken as the maximum scale.
    # When not set, the maximum value will be calculated automatically to ensure the uniform distribution of coordinate axis scale.
    # In the category axis, it can also be set as the ordinal number of the category (for example, in the category axis data: ['class A', 'class B', 'Class C'], the ordinal number 2 represents' Class C '.
    # It can also be set to a negative number, such as - 3).
    max_: Union[Numeric, str, None] = None,
    # Automatically calculated minimum axis spacing size.
    # For example, it can be set to 1 to ensure that the coordinate axis division scale is displayed as an integer.
    # The default value is 0
    min_interval: Numeric = 0,
    # Automatically calculated maximum axis spacing size.
    # For example, the time axis ((type: 'time') can be set to 3600 * 24 * 1000 to ensure that the maximum division scale of the coordinate axis is one day.
    max_interval: Optional[Numeric] = None,
    # Axis tick mark configuration item, reference ` global_options.AxisLineOpts`
    axisline_opts: Union[AxisLineOpts, dict, None] = None,
    # Axis scale configuration item, reference ` global_options.AxisTickOpts`
    axistick_opts: Union[AxisTickOpts, dict, None] = None,
    # Axis label configuration item, refer to ` series_options.LabelOpts`
    axislabel_opts: Union[LabelOpts, dict, None] = None,
    # Axis indicator configuration item, reference ` global_options.AxisPointerOpts`
    axispointer_opts: Union[AxisPointerOpts, dict, None] = None,
    # Text style of axis name, refer to ` series_options.TextStyleOpts`
    name_textstyle_opts: Union[TextStyleOpts, dict, None] = None,
    # Split region configuration item, refer to ` series_options.SplitAreaOpts`
    splitarea_opts: Union[SplitAreaOpts, dict, None] = None,
    # Split line configuration item, refer to ` series_options.SplitLineOpts`
    splitline_opts: Union[SplitLineOpts, dict] = SplitLineOpts(),
    # For settings related to axis minor scale lines, refer to ` series_options.MinorTickOpts`
    minor_tick_opts: Union[MinorTickOpts, dict, None] = None,
    # The secondary separation line of the coordinate axis in the grid area. The secondary division line will align with the secondary division line minorTick, refer to ` series_options.MinorSplitLineOpts`
    minor_split_line_opts: Union[MinorSplitLineOpts, dict, None] = None,
)
from PreTest import *
from pyecharts import options as opts
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot
 
from pyecharts.charts import Bar
 
x_data = [f"11 month{str(i)}day" for i in range(1, 12)]
y_total = [0, 900, 1245, 1530, 1376, 1376, 1511, 1689, 1856, 1495, 1292]
y_in = [900, 345, 393, "-", "-", 135, 178, 286, "-", "-", "-"]
y_out = ["-", "-", "-", 108, 154, "-", "-", "-", 119, 361, 203]
 
 
def bar_chart() -> Bar:
    # ********* Begin *********#  
    bar = (
            Bar()
            .add_xaxis(x_data)
            .add_yaxis("",y_total,stack="total",itemstyle_opts=opts.ItemStyleOpts(color="rgba(0,0,0,0)"),)
            .add_yaxis("income",y_in,stack="total")
            .add_yaxis("expenditure",y_out,stack="total")
            .set_global_opts(
                yaxis_opts=opts.AxisOpts(type_='value'),
                    )
 
        )
    # ********** End **********#
    return bar
 
make_snapshot(snapshot, bar_chart().render("Result/render.html"), "StudentAnswer/student_answer.png") # Output picture
make_snapshot(snapshot, bar_waterfall_plot(x_data, y_total, y_in, y_out).render(), "StandardAnswer/task2/standard_answer_2.png")

2.9 toolbox configuration items

Toolbars can be added to various charts to provide some auxiliary functions. The interface definition of toolbox configuration item is as follows:

class ToolboxOpts(
    # Show toolbar components
    is_show: bool = True,
    # The layout orientation of the toolbar icon.
    # Optional: 'horizontal', 'vertical'
    orient: str = "horizontal",
    # The distance from the toolbar component to the left of the container.
    # The value of left can be a specific pixel value such as 20 or a percentage relative to the height and width of the container such as' 20% ',
    # It can also be 'left', 'center', 'right'.
    # If the value of left is' left ',' center ',' right ', the components will align automatically according to the corresponding position
    pos_left: str = "80%",
    # The distance from the toolbar component to the right of the container.
    # The value of right can be a specific pixel value such as 20 or a percentage relative to the height and width of the container such as' 20% '.
    pos_right: Optional[str] = None,
    # The distance from the toolbar component to the upper side of the container.
    # The value of top can be a specific pixel value such as 20 or a percentage relative to the height and width of the container such as' 20% ',
    # It can also be 'top', 'middle', 'bottom'.
    # If the value of top is' top ',' middle ',' bottom ', the component will be aligned automatically according to the corresponding position.
    pos_top: Optional[str] = None,
    # The distance from the toolbar component to the underside of the container.
    # The value of bottom can be a specific pixel value such as 20 or a percentage relative to the height and width of the container such as' 20% '.
    pos_bottom: Optional[str] = None,
    # For each tool configuration item, refer to ` global_options.ToolBoxFeatureOpts`
    feature: Union[ToolBoxFeatureOpts, dict] = ToolBoxFeatureOpts(),
)

Toolbox tool configuration item

Set whether each type of tool is displayed through the toolbox tool configuration item:

class ToolBoxFeatureOpts(
    # Save as picture
    save_as_image: Union[ToolBoxFeatureSaveAsImageOpts, dict] = ToolBoxFeatureSaveAsImageOpts(),
    # Configuration item restore    
    restore: Union[ToolBoxFeatureRestoreOpts, dict] = ToolBoxFeatureRestoreOpts(),
    # The data view tool can display the data used by the current chart, which can be dynamically updated after editing
    data_view: Union[ToolBoxFeatureDataViewOpts, dict] = ToolBoxFeatureDataViewOpts(),
    # Data area scaling. (currently only supports the scaling of rectangular coordinate system)
    data_zoom: Union[ToolBoxFeatureDataZoomOpts, dict] = ToolBoxFeatureDataZoomOpts(),
    # Dynamic type switching.
    magic_type: Union[ToolBoxFeatureMagicTypeOpts, dict] = ToolBoxFeatureMagicTypeOpts(),
    # Controls for the checkbox component.
    brush: Union[ToolBoxFeatureBrushOpts, dict] = ToolBoxFeatureBrushOpts(),
)

Each of these tools also provides its own configuration items.

The toolbox check box component configuration item is defined as follows:

class ToolBoxFeatureBrushOpts(
    # Buttons used, values:
    # 'rect ': turn on the rectangular box selection function.
    # 'polygon': turn on the selection function of any shape box.
    # 'lineX': turn on the lateral selection function.
    # 'lineY': enable the vertical selection function.
    # 'keep': switch between "single selection" and "multi selection" modes. The latter can support drawing multiple selection boxes at the same time. The former supports clicking to clear all check boxes.
    # 'clear': clear all check boxes.
    type_: Optional[str] = None,
    # icon path for each button.
    rect_icon: Optional[JSFunc] = None,
    # icon path for each button.
    polygon_icon: Optional[JSFunc] = None,
    # icon path for each button.
    line_x_icon: Optional[JSFunc] = None,
    # icon path for each button.
    line_y_icon: Optional[JSFunc] = None,
    # icon path for each button.
    keep_icon: Optional[JSFunc] = None,
    # icon path for each button.
    clear_icon: Optional[JSFunc] = None,
    # Title text.
    rect_title: str = "rectangular selection",
    # Title text.
    polygon_title: str = "select by circling the candidates' names",
    # Title text.
    line_x_title: str = "Lateral selection",
    # Title text.
    line_y_title: str = "Vertical selection",
    # Title text.
    keep_title: str = "Keep selection",
    # Title text.
    clear_title: str = "clear selection",
)

The Toolbox dynamic type switching configuration item interface is defined as follows:

class ToolBoxFeatureMagicTypeOpts(
    # Whether to display the tool.
    is_show: bool = True,
    # Enabled dynamic types
    # Including 'line' (switch to line chart), 'bar' (switch to bar chart),
    # 'stack '(switch to stacking mode),' tiled '(switch to tiling mode).
    type_: Optional[Sequence] = None,    
    # Each type of title text can be configured separately.
    line_title: str = "Switch to line chart",
    # Each type of title text can be configured separately.
    bar_title: str = "Switch to histogram",
    # Each type of title text can be configured separately.
    stack_title: str = "Switch to stack",
    # Each type of title text can be configured separately.
    tiled_title: str = "Switch to tile",
    # Each type of icon path can be configured separately.
    line_icon: Optional[JSFunc] = None,
    # Each type of icon path can be configured separately.
    bar_icon: Optional[JSFunc] = None,
    # Each type of icon path can be configured separately.
    stack_icon: Optional[JSFunc] = None,
    # Each type of icon path can be configured separately.
    tiled_icon: Optional[JSFunc] = None,
)

Toolbox area scaling configuration item interface definition:

class ToolBoxFeatureDataZoomOpts(
    # Whether to display the tool.
    is_show: bool = True,
    # Prompt language
    zoom_title: str = "Area scaling",
    # Prompt language
    back_title: str = "Area zoom restore",
    # Can pass' image://url 'set as a picture, where the URL is a link to the picture, or a dataURI.
    zoom_icon: Optional[JSFunc] = None,
    # Can pass' image://url 'set as a picture, where the URL is a link to the picture, or a dataURI.
    back_icon: Optional[JSFunc] = None,
    # Specify which xAxis are controlled. If default, all x axes are controlled.
    # If set to false, no x-axis is controlled. If set to 3, the x-axis with axisIndex of 3 is controlled.
    # If set to [0, 3], the x-axis with axisIndex of 0 and 3 is controlled.
    xaxis_index: Union[Numeric, Sequence, bool] = None,
    # Specify which yAxis are controlled. If default, all y axes are controlled.
    # If set to false, no Y-axis is controlled. If set to 3, the y-axis with axisIndex of 3 is controlled.
    # If set to [0, 3], the y-axis with axisIndex of 0 and 3 is controlled.
    yaxis_index: Union[Numeric, Sequence, bool] = None,
    # The operation principle of dataZoom is to achieve the effect of data window scaling through data filtering and setting the axis display window inside.
    # 'filter': the data outside the current data window is filtered out. This will affect the data range of other axes.
    #  For each data item, as long as one dimension is outside the data window, the whole data item will be filtered out.
    # 'weakFilter': the data outside the current data window is filtered out. This will affect the data range of other axes.
    #  For each data item, the entire data item will be filtered out only when all dimensions are outside the same side of the data window.
    # 'empty': the data outside the current data window, which is set to empty. That is, the data range of other axes will not be affected.
    # 'none': do not filter data, only change the range of the number axis.
    filter_mode: str = "filter",
)
Toolbox data view tool

Toolbox data view tool interface definition:

class ToolBoxFeatureDataViewOpts(
    # Whether to display the tool.
    is_show: bool = True, 
    # Prompt language
    title: str = "reduction", 
    # Can pass' image://url 'set as a picture, where the URL is a link to the picture, or a dataURI.
    icon: Optional[JSFunc] = None
    # Is not editable (read-only). The default is False
    is_read_only: bool = False,
    # Customize the dataView presentation function to replace the default textarea and use richer data editing. You can return a dom object or an html string.
    option_to_content: Optional[JSFunc] = None,
    # When optionToContent is used, if the refresh after data editing is supported, the logic of assembling option needs to be realized through this function.
    content_to_option: Optional[JSFunc] = None,
    # There are three scripts on the data view. The default is ['data view', 'close', 'refresh].
    lang: Optional[Sequence[str]] = None,
    # Data view floating layer background color.
    background_color: str = "#fff",
    # Background color of data view floating layer text input area.
    text_area_color: str = "#fff",
    # Border color of data view floating layer text input area.
    text_area_border_color: str = "#333",
    # Text color.
    text_color: str = "#000",
    # Button color.
    button_color: str = "#c23531",
    # Button text color.
    button_text_color: str = "#fff",
)

Toolbox restore configuration item interface definition:

class ToolBoxFeatureRestoreOpts(
    # Whether to display the tool.
    is_show: bool = True, 
    # Prompt language
    title: str = "reduction", 
    # Can pass' image://url 'set as a picture, where the URL is a link to the picture, or a dataURI.
    icon: Optional[JSFunc] = None
)

Interface definition of image configuration item saved by Toolbox:

class ToolBoxFeatureSaveAsImageOpts(
    # Saved picture format. 'png' and 'jpeg' are supported.
    type_: str = "png",
    # The name of the saved file is title.text by default.
    name: Optional[str] = None,
    # The background color of the saved picture is backgroundColor by default. If the backgroundColor does not exist, it will be white.
    background_color: str = "auto",
    # If charts use charts.connect to link multiple charts, these linked charts will be exported when exporting pictures. This configuration item determines the fill color at the gap between the chart and the chart.
    connected_background_color: str = "#fff",
    # List of components ignored when saving as a picture. The toolbar is ignored by default.
    exclude_components: Optional[Sequence[str]] = None,
    # Whether to display the tool.
    is_show: bool = True,
    # Prompt language
    title: str = "Save as picture",
    # Can pass' image://url 'set as a picture, where the URL is a link to the picture, or a dataURI.
    icon: Optional[JSFunc] = None,
    # The resolution scale of the saved picture is the same as the container by default. If you need to save a higher resolution, you can set it to a value greater than 1, such as 2.
    pixel_ratio: Numeric = 1,
)

2.10 mark point data items

In the actual drawing, there will be a need to mark the icon. You can use the mark point, mark line and mark area configuration items in the series configuration items to make corresponding settings.

from PreTest import *
from pyecharts import options as opts
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot
 
from pyecharts.charts import Bar
 
from pyecharts.faker import Faker
 
data_x = Faker.choose()
data_y_1 = Faker.values()
data_y_2 = Faker.values()
 
 
def bar_chart() -> Bar:
    # ********* Begin *********#  
    bar = (
        Bar()
        .add_xaxis(data_x)
        .add_yaxis("business A", data_y_1)
        .add_yaxis(
            "business B", 
            data_y_2,
            markpoint_opts=opts.MarkPointOpts(
                data=[
                    opts.MarkPointItem(
                    name="Custom marker point", 
                    coord=[data_x[2], data_y_2[2]], 
                    value=data_y_2[2]
                    )
                    ]
                ),
            )
        .set_global_opts(title_opts=opts.TitleOpts(title="Bar-MarkLine((specify type)"))
        .set_series_opts(
            label_opts=opts.LabelOpts(is_show=False),
            markline_opts=opts.MarkLineOpts(
                data=[
                    opts.MarkLineItem(type_="min", name="minimum value"),
                    opts.MarkLineItem(type_="max", name="Maximum"),
                    opts.MarkLineItem(type_="average", name="average value"),
                ]
            ),
        )
    )
    # ********** End **********#
    return bar
 
make_snapshot(snapshot, bar_chart().render("Result/render.html"), 'StudentAnswer/student_answer.png') # Output picture
make_snapshot(snapshot, bar_mark(data_x, data_y_1, data_y_2).render(), "StandardAnswer/task4/standard_answer_4.png")

2.11 area scaling configuration item

We learned to use the area scaling function in the toolbox. In addition, the global configuration item of pyecarts also provides an area scaling configuration item to set the scaling effect.

Its interface is defined as follows:

class DataZoomOpts(
    # Whether to display components. If it is set to false, it will not be displayed, but the data filtering function still exists.
    is_show: bool = True,
    # Component type, optional "slider", "inside"
    type_: str = "slider",
    # Whether to update the view of the series in real time when dragging. If it is set to false, it is updated only at the end of the drag.
    is_realtime: bool = True,
    # The starting percentage of the data window range. The range is: 0 ~ 100. Indicates 0% - 100%.
    range_start: Union[Numeric, None] = 20,
    # The end percentage of the data window range. Range: 0 ~ 100
    range_end: Union[Numeric, None] = 80,
    # The starting value of the data window range. If start is set, startValue is invalid.
    start_value: Union[int, str, None] = None,
    # The end value of the data window range. If end is set, endValue is invalid.
    end_value: Union[int, str, None] = None,
    # Whether the layout is horizontal or vertical. Not only the layout mode, but also the rectangular coordinate system determines whether the horizontal number axis or the vertical number axis is controlled by default
    # The optional values are: 'horizontal', 'vertical'
    orient: str = "horizontal",
    # Set the x-axis controlled by the datazoom inside component (that is, xAxis, which is a concept in the rectangular coordinate system, see grid).
    # When not specified, when dataZoom-inside.orient is' horizontal ', the first xAxis parallel to dataZoom is controlled by default
    # If it is number, it means to control one axis; if it is Array, it means to control multiple axes.
    xaxis_index: Union[int, Sequence[int], None] = None,
    # Set the y-axis controlled by the datazoom inside component (that is, yAxis, which is a concept in the rectangular coordinate system, see grid).
    # When not specified, when dataZoom-inside.orient is' horizontal ', the first yAxis parallel to dataZoom is controlled by default
    # If it is number, it means to control one axis; if it is Array, it means to control multiple axes.
    yaxis_index: Union[int, Sequence[int], None] = None,
    # Whether to lock the size of the selection area (or data window).
    # If set to true, the size of the selection area is locked, that is, it can only be panned, not zoomed.
    is_zoom_lock: bool = False,
    # The distance from the datazoom slider component to the left side of the container.
    # The value of left can be a specific pixel value such as 20 or a percentage relative to the height and width of the container such as' 20% ',
    # It can also be 'left', 'center', 'right'.
    # If the value of left is' left ',' center ',' right ', the components will be aligned automatically according to the corresponding position.
    pos_left: Optional[str] = None,
    # The distance from the datazoom slider assembly to the upper side of the container.
    # The value of top can be a specific pixel value such as 20 or a percentage relative to the height and width of the container such as' 20% ',
    # It can also be 'top', 'middle', 'bottom'.
    # If the value of top is' top ',' middle ',' bottom ', the component will be aligned automatically according to the corresponding position.
    pos_top: Optional[str] = None,
    # The distance from the datazoom slider component to the right side of the container.
    # The value of right can be a specific pixel value such as 20 or a percentage relative to the height and width of the container such as' 20% '.
    # Default adaptation.
    pos_right: Optional[str] = None,
    # The distance from the datazoom slider assembly to the underside of the container.
    # The value of bottom can be a specific pixel value such as 20 or a percentage relative to the height and width of the container such as' 20% '.
    # Default adaptation.
    pos_bottom: Optional[str] = None,
    # The operation principle of dataZoom is to achieve the effect of data window scaling through data filtering and setting the axis display window inside.
    # 'filter': the data outside the current data window is filtered out. This will affect the data range of other axes.
    #  For each data item, as long as one dimension is outside the data window, the whole data item will be filtered out.
    # 'weakFilter': the data outside the current data window is filtered out. This will affect the data range of other axes.
    #  For each data item, the entire data item will be filtered out only when all dimensions are outside the same side of the data window.
    # 'empty': the data outside the current data window, which is set to empty. That is, the data range of other axes will not be affected.
    # 'none': do not filter data, only change the range of the number axis.
    filter_mode: str = "filter"
)
from PreTest import *
from pyecharts import options as opts
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot
 
from pyecharts.charts import Bar
 
from pyecharts.faker import Faker
 
data_x = Faker.days_attrs
data_y = Faker.days_values
color = Faker.rand_color()
 
 
def bar_chart() -> Bar:
    # ********* Begin *********#  
    bar = (
        Bar()
        .add_xaxis(data_x)
        .add_yaxis("business A",data_y,color=color)
        .set_global_opts(
            title_opts=opts.TitleOpts(title="Bar-DataZoom(slider+inside)"),
            datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")], 
        )
 
    )
    # ********** End **********#
    return bar
 
make_snapshot(snapshot, bar_chart().render("Result/render.html"), 'StudentAnswer/student_answer.png') # Output picture
make_snapshot(snapshot, bar_datazoom(data_x, data_y, color).render(), "StandardAnswer/task5/standard_answer_5.png")


You can zoom and scroll by dragging the following slider or sliding the wheel within the chart:

3. Broken line / area diagram of pyecharts rectangular coordinate system chart

3.1 import required packages

from pyecharts.charts import Line
x_data = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
y_data = [820, 932, 901, 934, 1290, 1330, 1320]

3.2 line chart data items

The data item interface of line chart is as follows:

class LineItem(
    # Data item name.
    name: Union[str, Numeric] = None,
    # The value of the data item
    value: Union[str, Numeric] = None,
    # A graph of a single data tag.
    symbol: Optional[str] = None,
    # Size of individual data markers
    symbol_size: Union[Sequence[Numeric], Numeric] = None,
    # The rotation angle (not radians) of a single data marker.
    symbol_rotate: Optional[Numeric] = None,
    # If the symbol is in the form of path: / /, whether to maintain the aspect ratio of the figure when zooming.
    symbol_keep_aspect: bool = False,
    # The offset of a single data marker from its original position.
    symbol_offset: Optional[Sequence] = None,
    # Label configuration item, refer to ` series_options.LabelOpts`
    label_opts: Union[LabelOpts, dict, None] = None,
    # Element style configuration item, refer to ` series_options.ItemStyleOpts`
    itemstyle_opts: Union[ItemStyleOpts, dict, None] = None,
    # Prompt box component configuration item, refer to ` series_options.TooltipOpts`
    tooltip_opts: Union[TooltipOpts, dict, None] = None,
)

3.3 Y-axis configuration items of line chart

The Y-axis configuration interface of the broken line diagram is as follows:

def add_yaxis(
    # Series name, used for displaying tooltip and legend filtering of legend.
    series_name: str,
    # Series data
    y_axis: types.Sequence[types.Union[opts.LineItem, dict]],
    # Check legend
    is_selected: bool = True,
    # Whether to connect empty data. Empty data is filled with 'None'
    is_connect_nones: bool = False,
    # The x-axis index used is useful when there are multiple X-axes in a single chart instance.
    xaxis_index: Optional[Numeric] = None,
    # The y-axis index used is useful when there are multiple Y-axes in a single chart instance.
    yaxis_index: Optional[Numeric] = None,
    # Series label colors
    color: Optional[str] = None,
    # Whether to display symbol. If false, it will be displayed only when tooltip hover is selected.
    is_symbol_show: bool = True,
    # Marked graphics.
    # The tag types provided by ecarts include 'circle', 'rect', 'roundRect', 'triangle', 
    # 'diamond', 'pin', 'arrow', 'none'
    # Can pass' image://url 'set as a picture, where the URL is a link to the picture, or a dataURI.
    symbol: Optional[str] = None,
    # The size of the tag can be set to a single number such as 10, or the width and height can be separated by an array,
    # For example, [20, 10] indicates that the width of the mark is 20 and the height is 10.
    symbol_size: Union[Numeric, Sequence] = 4,
    # Data stacking: the series on the same category axis can be stacked with the same stack value.
    stack: Optional[str] = None,
    # Smooth curve
    is_smooth: bool = False,
    # Whether to crop the drawing beyond the coordinate system. Broken line graph: cut off all broken lines beyond the coordinate system, and the logic of inflection point graph shall be processed according to the scatter diagram
    is_clip: bool = True,
    # Is it displayed as a ladder diagram
    is_step: bool = False,
    # Whether to enable the prompt animation effect of hover on the inflection point sign.
    is_hover_animation: bool = True,
    # The zlevel value of all figures in the line chart.
    # Zlevel is used for canvas layering. Graphics with different zlevel values will be placed in different canvas. Canvas layering is a common optimization method.
    # The large Canvas of zlevel will be placed on the small Canvas of zlevel.
    z_level: types.Numeric = 0,
    # The z value of all figures of the line chart component. Controls the sequence of drawings. A graph with a small z value will be overwritten by a graph with a large z value.
    # z has lower priority than zlevel, and no new Canvas will be created.
    z: types.Numeric = 0,
    # Marker point configuration item, refer to ` series_options.MarkPointOpts`
    markpoint_opts: Union[opts.MarkPointOpts, dict, None] = None,
    # Marker line configuration item, refer to ` series_options.MarkLineOpts`
    markline_opts: Union[opts.MarkLineOpts, dict, None] = None,
    # Prompt box component configuration item, refer to ` series_options.TooltipOpts`
    tooltip_opts: Union[opts.TooltipOpts, dict, None] = None,
    # Label configuration item, refer to ` series_options.LabelOpts`
    label_opts: Union[opts.LabelOpts, dict] = opts.LabelOpts(),
    # Line style configuration item, refer to ` series_options.LineStyleOpts`
    linestyle_opts: Union[opts.LineStyleOpts, dict] = opts.LineStyleOpts(),
    # Fill area configuration item, refer to ` series_options.AreaStyleOpts`
    areastyle_opts: Union[opts.AreaStyleOpts, dict] = opts.AreaStyleOpts(),
    # Element style configuration item, refer to ` series_options.ItemStyleOpts`
    itemstyle_opts: Union[opts.ItemStyleOpts, dict, None] = None,
)
  • The x-axis data is set to x_data

  • Y-axis data series name is set to null, and y-axis data is used_ Data, select "emptyCircle" for the marked graph and display the label

  • Do not display prompt box components

  • The X axis is set as the category axis

  • The Y axis is set as the numerical axis to display the coordinate axis scale and division line

from PreTest import *
from pyecharts import options as opts
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot
 
from pyecharts.charts import Line
 
 
x_data = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
y_data = [820, 932, 901, 934, 1290, 1330, 1320]
 
 
def line_chart() -> Line:
    # ********* Begin *********#  
    line = (
        Line()
        .add_xaxis(x_data)
        .add_yaxis("",y_data,symbol='emptyCircle',is_symbol_show=True,label_opts=opts.LabelOpts(is_show=False))
        .set_global_opts(
            tooltip_opts=opts.TooltipOpts(is_show=False),
            xaxis_opts=opts.AxisOpts(
                type_="category"
            ),
            yaxis_opts=opts.AxisOpts(
                type_="value",
                axistick_opts=opts.AxisTickOpts(is_show=True),
                splitline_opts=opts.SplitLineOpts(is_show=True)
            ),
        )
    )
    # ********** End **********#
    return line
 
make_snapshot(snapshot, line_chart().render("Result/render.html"), 'StudentAnswer/student_answer.png') # Output picture
make_snapshot(snapshot, line_base(x_data, y_data).render(), "StandardAnswer/task1/standard_answer_1.png")

3.4 area fill pattern configuration item

class AreaStyleOpts(
    # Graphics transparency. Numbers from 0 to 1 are supported. When it is 0, the figure will not be drawn.
    opacity: Optional[Numeric] = 0,
    # The color of the fill.
    # Colors can be expressed in RGB, such as' rgb(128, 128, 128) '. If you want to add alpha channel to represent opacity,
    # have access to RGBA,such as 'rgba(128, 128, 128, 0.5)',You can also use hexadecimal format, such as '#ccc'. 
    # In addition to solid colors, colors also support gradient and texture filling
    # 
    # Linear gradient. The first four parameters are x0, Y0, X2 and Y2, ranging from 0 to 1, which is equivalent to the percentage in the graphic bounding box,
    # If globalCoord is' true ', the four values are absolute pixel positions
    # color: {
    #    type: 'linear',
    #    x: 0,
    #    y: 0,
    #    x2: 0,
    #    y2: 1,
    #    colorStops: [{
    #        Offset: 0, color: 'Red' / / color at 0%
    #    }, {
    #        Offset: 1, color: 'Blue' / / color at 100%
    #    }],
    #    global: false / / the default value is false
    # }
    # 
    # Radial gradient: the first three parameters are circle center x, y and radius, and the values are the same as linear gradient
    # color: {
    #    type: 'radial',
    #    x: 0.5,
    #    y: 0.5,
    #    r: 0.5,
    #    colorStops: [{
    #        Offset: 0, color: 'Red' / / color at 0%
    #    }, {
    #        Offset: 1, color: 'Blue' / / color at 100%
    #    }],
    #    global: false / / the default value is false
    # }
    # 
    # Texture fill
    # color: {
    #    image: imageDom, / / htmlimageelement and htmlcanvas element are supported, but path string is not supported
    #    repeat: 'repeat' / / whether to tile. It can be 'repeat-x', 'repeat-y', 'no repeat'
    # }
    color: Optional[str] = None
)
X Axis data item usage data_x

Add two groups Y Axis data. The first set of series names is set to "merchant" A",Data usage data_y_1,Area fill transparency is set to 0.5

Set the name of the second group of series to "merchant" B",Data usage data_y_2,Area fill transparency is set to 0.5

Title set to“ Line-Area map
from PreTest import *
from pyecharts import options as opts
from pyecharts.faker import Faker
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot
 
from pyecharts.charts import Line
 
data_x = Faker.choose()
data_y_1 = Faker.values()
data_y_2 = Faker.values()
 
 
def line_chart() -> Line:
    # ********* Begin *********#  
    line = (
        Line()
        .add_xaxis(data_x)
        .add_yaxis("business A",data_y_1)
        .add_yaxis("business B",data_y_2)
        .set_global_opts(
            title_opts=opts.TitleOpts(title="Line-Area map")
            
        )
        .set_series_opts(
            areastyle_opts=opts.AreaStyleOpts(opacity=0.5)
        )
    )
    # ********** End **********#
    return line
 
make_snapshot(snapshot, line_chart().render("Result/render.html"), "StudentAnswer/student_answer.png") # Output picture
make_snapshot(snapshot, line_area_style(data_x, data_y_1, data_y_2).render(), "StandardAnswer/task2/standard_answer_2.png")

3.5 line style configuration items

class LineStyleOpts(
    # Show
    is_show: bool = True,
    # Line width.
    width: Numeric = 1,
    # Graph transparency. Supports numbers from 0 to 1. When it is 0, the graph will not be drawn.
    opacity: Numeric = 1,
    # The curvature of the line, 0 means no bending at all
    curve: Numeric = 0,
    # Type of line. Optional:
    # 'solid', 'dashed', 'dotted'
    type_: str = "solid",
    # The color of the line.
    # Colors can be expressed in RGB, such as' rgb(128, 128, 128) '. If you want to add alpha channel to represent opacity,
    # have access to RGBA,such as 'rgba(128, 128, 128, 0.5)',You can also use hexadecimal format, such as '#ccc'. 
    # In addition to solid colors, colors also support gradient and texture filling
    # 
    # Linear gradient. The first four parameters are x0, Y0, X2 and Y2, ranging from 0 to 1, which is equivalent to the percentage in the graphic bounding box,
    # If globalCoord is' true ', the four values are absolute pixel positions
    # color: {
    #    type: 'linear',
    #    x: 0,
    #    y: 0,
    #    x2: 0,
    #    y2: 1,
    #    colorStops: [{
    #        Offset: 0, color: 'Red' / / color at 0%
    #    }, {
    #        Offset: 1, color: 'Blue' / / color at 100%
    #    }],
    #    global: false / / the default value is false
    # }
    # 
    # Radial gradient: the first three parameters are circle center x, y and radius, and the values are the same as linear gradient
    # color: {
    #    type: 'radial',
    #    x: 0.5,
    #    y: 0.5,
    #    r: 0.5,
    #    colorStops: [{
    #        Offset: 0, color: 'Red' / / color at 0%
    #    }, {
    #        Offset: 1, color: 'Blue' / / color at 100%
    #    }],
    #    global: false / / the default value is false
    # }
    # 
    # Texture fill
    # color: {
    #    image: imageDom, / / htmlimageelement and htmlcanvas element are supported, but path string is not supported
    #    repeat: 'repeat' / / whether to tile. It can be 'repeat-x', 'repeat-y', 'no repeat'
    # }
    color: Union[str, Sequence, None] = None,
)
X Axis data item usage data_x

Y Set the axis data series name to merchant A"",Data usage data_y,Marked graphic selection“ triangle",The size is 20, the line style color is set to green, the width is 4, and the type is“ dashed",The element color is set to blue, the border width is 3, and the border color is set to yellow

Title set to“ Line-ItemStyle"
from PreTest import *
from pyecharts import options as opts
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot
 
from pyecharts.charts import Line
 
from pyecharts.faker import Faker
 
data_x = Faker.choose()
data_y = Faker.values()
 
 
def line_chart() -> Line:
    # ********* Begin *********#  
    line = (
        Line()
        .add_xaxis(data_x)
        .add_yaxis(
            "business A",
            data_y,
            symbol_size=20,
            symbol='triangle',
            linestyle_opts=opts.LineStyleOpts(width=4,type_='dashed',color='green'),
            itemstyle_opts=opts.ItemStyleOpts(border_width=3,border_color="yellow",color='blue')
            )
        .set_global_opts(
            title_opts=opts.TitleOpts(title="Line-ItemStyle")
        )
 
    )
    # ********** End **********#
    return line
 
make_snapshot(snapshot, line_chart().render("Result/render.html"), 'StudentAnswer/student_answer.png') # Output picture
make_snapshot(snapshot, line_itemstyle(data_x, data_y).render(), "StandardAnswer/task3/standard_answer_3.png")

The image canvas size is initialized to 1600 pixels wide and 800 pixels high

X Axis data item usage x_data

Add three groups Y Axis data. The first set of series names is set to "1"/2 Index ", data use y_data_05,The line width is set to 2

The name of the second group of series is set to "index of 2", and the data is used y_data_2,The line width is set to 2

The name of the third group of series is set to "index of 3", and the data is used y_data_3,The line width is set to 2

The title is set to "logarithmic axis example", which is displayed in the center

The prompt box trigger type is set to data item graphic trigger and formatted as{a} <br/>{b} : {c}

Displays the legend to the left

X The axis is set as category axis, and the name is“ x"

Y Axis coordinate axis type is set to logarithmic axis, and the name is“ y",Displays split lines and supports scaling
from PreTest import *
from pyecharts import options as opts
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot
 
from pyecharts.charts import Line
 
x_data = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
y_data_3 = [1, 3, 9, 27, 81, 247, 741, 2223, 6669]
y_data_2 = [1, 2, 4, 8, 16, 32, 64, 128, 256]
y_data_05 = [1 / 2, 1 / 4, 1 / 8, 1 / 16, 1 / 32, 1 / 64, 1 / 128, 1 / 256, 1 / 512]
 
 
def line_chart() -> Line:
    # ********* Begin *********#  
    line = (
        Line(init_opts=opts.InitOpts(width="1600px", height="800px"))
        .add_xaxis(xaxis_data=x_data)
        .add_yaxis(
            series_name="1/2 Index of",
            y_axis=y_data_05,
            linestyle_opts=opts.LineStyleOpts(width=2),
        )
        .add_yaxis(
            series_name="2 Index of", y_axis=y_data_2, linestyle_opts=opts.LineStyleOpts(width=2)
        )
        .add_yaxis(
            series_name="3 Index of", y_axis=y_data_3, linestyle_opts=opts.LineStyleOpts(width=2)
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(title="Logarithmic axis example", pos_left="center"),
            tooltip_opts=opts.TooltipOpts(trigger="item", formatter="{a} <br/>{b} : {c}"),
            legend_opts=opts.LegendOpts(pos_left="left"),
            xaxis_opts=opts.AxisOpts(type_="category", name="x"),
            yaxis_opts=opts.AxisOpts(
                type_="log",
                name="y",
                splitline_opts=opts.SplitLineOpts(is_show=True),
                is_scale=True,
            ),
        )
    )
    # ********** End **********#
    return line
 
make_snapshot(snapshot, line_chart().render("Result/render.html"), 'StudentAnswer/student_answer.png') # Output picture
make_snapshot(snapshot, line_log_axis(x_data, y_data_05, y_data_2, y_data_3).render(), "StandardAnswer/task4/standard_answer_4.png")

X Axis data item usage data_x_1

expand X Axis, data usage data_x_2,The type is set to category axis to ensure that the scale line and label are aligned. The axis does not have to be on the 0 scale of another axis, and the color is set to“#6e9ef1 ", display the axis indicator and format it as js_formatter

Add two groups Y Axis data. The name of the first group of series is set as "2015 precipitation". See the end of the text for the data, smooth the curve, and set the marked graph as“ emptyCircle",stay tooltip hover Display when symbol,Color set to“#d14a61 ", no label is displayed, and the lineweight is set to 2

The name of the second group of series is set as "2016 precipitation", see the end of the text for the data, smooth the curve, and set the marked graph as“ emptyCircle",stay tooltip hover Display when symbol,Color set to“#6e9ef1 ", no label is displayed, and the lineweight is set to 2

Display legend, prompt box trigger type, select data item graphic trigger, and the type is crosshair indicator

X The axis is set as category axis, the tick mark and label alignment are set, and the axis color is set as“#d14a61 ", display the axis indicator and format it as js_formatter

Y The axis coordinate axis type is set to numeric axis, and the split line transparency is set to 1
from PreTest import *
from pyecharts import options as opts
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot
from pyecharts.commons.utils import JsCode
 
from pyecharts.charts import Line
 
js_formatter = """function (params) {
        console.log(params);
        return 'precipitation  ' + params.value + (params.seriesData.length ? ': ' + params.seriesData[0].data : '');
    }"""
 
 
data_x_1 = [
    "2016-1",
    "2016-2",
    "2016-3",
    "2016-4",
    "2016-5",
    "2016-6",
    "2016-7",
    "2016-8",
    "2016-9",
    "2016-10",
    "2016-11",
    "2016-12",
]
 
data_x_2 = [
    "2015-1",
    "2015-2",
    "2015-3",
    "2015-4",
    "2015-5",
    "2015-6",
    "2015-7",
    "2015-8",
    "2015-9",
    "2015-10",
    "2015-11",
    "2015-12",
]
 
 
def line_chart() -> Line:
    # ********* Begin *********#  
    line = (
        Line(init_opts=opts.InitOpts(width="1600px", height="800px"))
    .add_xaxis(data_x_1)
    .extend_axis(
        xaxis_data=data_x_2,
        xaxis=opts.AxisOpts(
            type_="category",
            axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
            axisline_opts=opts.AxisLineOpts(
                is_on_zero=False, linestyle_opts=opts.LineStyleOpts(color="#6e9ef1")
            ),
            axispointer_opts=opts.AxisPointerOpts(
                is_show=True, label=opts.LabelOpts(formatter=JsCode(js_formatter))
            ),
        ),
    )
    .add_yaxis(
        series_name="2015 precipitation",
        is_smooth=True,
        symbol="emptyCircle",
        is_symbol_show=False,
        # xaxis_index=1,
        color="#d14a61",
        y_axis=[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3],
        label_opts=opts.LabelOpts(is_show=False),
        linestyle_opts=opts.LineStyleOpts(width=2),
    )
    .add_yaxis(
        series_name="2016 precipitation",
        is_smooth=True,
        symbol="emptyCircle",
        is_symbol_show=False,
        color="#6e9ef1",
        y_axis=[3.9, 5.9, 11.1, 18.7, 48.3, 69.2, 231.6, 46.6, 55.4, 18.4, 10.3, 0.7],
        label_opts=opts.LabelOpts(is_show=False),
        linestyle_opts=opts.LineStyleOpts(width=2),
    )
    .set_global_opts(
        legend_opts=opts.LegendOpts(),
        tooltip_opts=opts.TooltipOpts(trigger="none", axis_pointer_type="cross"),
        xaxis_opts=opts.AxisOpts(
            type_="category",
            axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
            axisline_opts=opts.AxisLineOpts(
                is_on_zero=False, linestyle_opts=opts.LineStyleOpts(color="#d14a61")
            ),
            axispointer_opts=opts.AxisPointerOpts(
                is_show=True, label=opts.LabelOpts(formatter=JsCode(js_formatter))
            ),
        ),
        yaxis_opts=opts.AxisOpts(
            type_="value",
            splitline_opts=opts.SplitLineOpts(
                is_show=True, linestyle_opts=opts.LineStyleOpts(opacity=1)
            ),
        ),
    )
 
    )
    # ********** End **********#
    return line
 
make_snapshot(snapshot, line_chart().render("Result/render.html"), 'StudentAnswer/student_answer.png') # Output picture
make_snapshot(snapshot, line_multiple_x_axis(data_x_1, data_x_2, js_formatter).render(), "StandardAnswer/task5/standard_answer_5.png")

The image canvas size is initialized to 1600 pixels wide and 800 pixels high

X Axis data item usage x_data

Y The axis data series name is set to "power consumption", and the data is used y_data,Set smooth, no labels are displayed, and the lineweight is set to 2

The title is set to "one day power consumption distribution" and the subtitle is set to "pure fiction"

The trigger type of the prompt box component is set to data item graphic trigger, and the indicator type is crosshair indicator

X No blank on both sides of axis coordinate

Y Format axis labels as{value} W,Show split lines

The visual mapping component is set to segment type, and the dimension is set to 0. See the end of the text for the scope of each segment

Add two marker areas named "morning peak" and "evening peak" to the screen of the relative container x The coordinates are set to("07:30", "10:00")and("17:30", "21:15")
from PreTest import *
from pyecharts import options as opts
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot
 
from pyecharts.charts import Line
 
 
x_data = [
    "00:00",
    "01:15",
    "02:30",
    "03:45",
    "05:00",
    "06:15",
    "07:30",
    "08:45",
    "10:00",
    "11:15",
    "12:30",
    "13:45",
    "15:00",
    "16:15",
    "17:30",
    "18:45",
    "20:00",
    "21:15",
    "22:30",
    "23:45",
]
y_data = [
    300,
    280,
    250,
    260,
    270,
    300,
    550,
    500,
    400,
    390,
    380,
    390,
    400,
    500,
    600,
    750,
    800,
    700,
    600,
    400,
]
 
 
def line_chart() -> Line:
    # ********* Begin *********#  
    line = (
        Line(init_opts=opts.InitOpts(width="1600px", height="800px"))
        .add_xaxis(x_data)
        .add_yaxis(
            series_name="Electricity consumption",
            y_axis=y_data,
            is_smooth=True,
            label_opts=opts.LabelOpts(is_show=False),
            linestyle_opts=opts.LineStyleOpts(width=2),
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(title="Daily power consumption distribution", subtitle="It's pure fiction"),
            tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"),
            xaxis_opts=opts.AxisOpts(boundary_gap=False),
            yaxis_opts=opts.AxisOpts(
                axislabel_opts=opts.LabelOpts(formatter="{value} W"),
                splitline_opts=opts.SplitLineOpts(is_show=True),
            ),
            visualmap_opts=opts.VisualMapOpts(
                is_piecewise=True,
                dimension=0,
                pieces=[
                    {"lte": 6, "color": "green"},
                    {"gt": 6, "lte": 8, "color": "red"},
                    {"gt": 8, "lte": 14, "color": "green"},
                    {"gt": 14, "lte": 17, "color": "red"},
                    {"gt": 17, "color": "green"},
                ],
            ),
        )
        .set_series_opts(
            markarea_opts=opts.MarkAreaOpts(
                data=[
                    opts.MarkAreaItem(name="Morning peak", x=("07:30", "10:00")),
                    opts.MarkAreaItem(name="Late peak", x=("17:30", "21:15")),
                ]
            )
        )
    )
 
    # ********** End **********#
    return line
 
make_snapshot(snapshot, line_chart().render("Result/render.html"), 'StudentAnswer/student_answer.png') # Output picture
make_snapshot(snapshot, line_distribution_of_electricity(x_data, y_data).render(), "StandardAnswer/task6/standard_answer_6.png")

The image canvas size is initialized to 1600 pixels wide and 800 pixels high

X Axis data item usage week_name_list

Add two groups Y Axis data. The name of the first set of series is set to "maximum temperature", and the data is used high_temperature,Add two marker points to mark the maximum and minimum values respectively, and add a dimension line to mark the average value

The name of the second group of series is set to "minimum temperature", and the data is used low_temperature,Add a marker point, name it "week minimum", and set the value to -2,Screen relative to container x The coordinates are set to 1, relative to the screen of the container y Set coordinates to -1.5;Add three dimension lines.

First dimension line dimension average

Second dimension line, graphic selection of end mark“ none",Screen relative to container x The coordinates are set to 90%,Screen relative to container y Set coordinates to max;

Third dimension line, graphic selection of end mark“ circle",Type selection“ max",Named "highest point"

The title is set to "temperature change in the next week" and the subtitle is set to "pure fiction"

Prompt box trigger type select coordinate axis trigger

show the toolbox

X Axis the coordinate axis type is set to category axis, and there is no blank on both sides of the coordinate axis
from PreTest import *
from pyecharts import options as opts
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot
 
from pyecharts.charts import Line
 
from pyecharts.faker import Faker
 
week_name_list = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
high_temperature = [11, 11, 15, 13, 12, 13, 10]
low_temperature = [1, -2, 2, 5, 3, 2, 0]
 
 
def line_chart() -> Line:
    # ********* Begin *********#  
    line = (
        Line(init_opts=opts.InitOpts(width="1600px", height="800px"))
        .add_xaxis(xaxis_data=week_name_list)
        .add_yaxis(
            series_name="Maximum temperature",
            y_axis=high_temperature,
            markpoint_opts=opts.MarkPointOpts(
                data=[
                    opts.MarkPointItem(type_="max", name="Maximum"),
                    opts.MarkPointItem(type_="min", name="minimum value"),
                ]
            ),
            markline_opts=opts.MarkLineOpts(
                data=[opts.MarkLineItem(type_="average", name="average value")]
            ),
        )
        .add_yaxis(
            series_name="Minimum temperature",
            y_axis=low_temperature,
            markpoint_opts=opts.MarkPointOpts(
                data=[opts.MarkPointItem(value=-2, name="Weekly minimum", x=1, y=-1.5)]
            ),
            markline_opts=opts.MarkLineOpts(
                data=[
                    opts.MarkLineItem(type_="average", name="average value"),
                    opts.MarkLineItem(symbol="none", x="90%", y="max"),
                    opts.MarkLineItem(symbol="circle", type_="max", name="the peak"),
                ]
            ),
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(title="Temperature change in the next week", subtitle="It's pure fiction"),
            tooltip_opts=opts.TooltipOpts(trigger="axis"),
            toolbox_opts=opts.ToolboxOpts(is_show=True),
            xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False),
        )
 
    )
    # ********** End **********#
    return line
 
make_snapshot(snapshot, line_chart().render("Result/render.html"), 'StudentAnswer/student_answer.png') # Output picture
make_snapshot(snapshot, line_temperature_change(week_name_list, high_temperature, low_temperature).render(), "StandardAnswer/task7/standard_answer_7.png")

X Shaft use x_data data

Add five groups Y Axis data. The first set of series name is set to "mail marketing", the data stack is set to "total", and the data is used y_data_1,Area fill transparency is set to 0.5,Do not display labels

The name of the second group of series is set to "alliance advertising", the data stack is set to "total", and the data is used y_data_2,Area fill transparency is set to 0.5,Do not display labels

The name of the third group of series is set to "video advertising", the data stack is set to "total", and the data is used y_data_3,Area fill transparency is set to 0.5,Do not display labels

The name of the fourth group of series is set to "direct access", the data stack is set to "total", and the data is used y_data_4,Area fill transparency is set to 0.5,Do not display labels

The name of the fifth group of series is set to "search engine", the data stack is set to "total", and the data is used y_data_5,Area fill transparency is set to 0.5,Display label with position set to“ top"

Set the title to stacked area map

The trigger type of the prompt box component is set to coordinate axis trigger, and the indicator type is crosshair indicator

Y The axis type is set to numerical axis, and the coordinate axis scale and division line are displayed

X The axis type is set to category axis, and there is no blank on both sides of the coordinate axis
from PreTest import *
from pyecharts import options as opts
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot
 
 
from pyecharts.charts import Line
 
x_data = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
 
y_data_1 = [120, 132, 101, 134, 90, 230, 210]
y_data_2 = [220, 182, 191, 234, 290, 330, 310]
y_data_3 = [150, 232, 201, 154, 190, 330, 410]
y_data_4 = [320, 332, 301, 334, 390, 330, 320]
y_data_5 = [820, 932, 901, 934, 1290, 1330, 1320]
 
def line_chart() -> Line:
    # ********* Begin *********#  
    line = (
 
        Line()
        .add_xaxis(xaxis_data=x_data)
        .add_yaxis(
            series_name="Mail marketing",
            stack="total",
            y_axis=[120, 132, 101, 134, 90, 230, 210],
            areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
            label_opts=opts.LabelOpts(is_show=False),
        )
        .add_yaxis(
            series_name="Alliance advertising",
            stack="total",
            y_axis=[220, 182, 191, 234, 290, 330, 310],
            areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
            label_opts=opts.LabelOpts(is_show=False),
        )
            .add_yaxis(
            series_name="Video advertising",
            stack="total",
            y_axis=[150, 232, 201, 154, 190, 330, 410],
            areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
            label_opts=opts.LabelOpts(is_show=False),
        )
        .add_yaxis(
            series_name="Direct access",
            stack="total",
            y_axis=[320, 332, 301, 334, 390, 330, 320],
            areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
            label_opts=opts.LabelOpts(is_show=False),
        )
        .add_yaxis(
            series_name="Search Engines",
            stack="total",
            y_axis=[820, 932, 901, 934, 1290, 1330, 1320],
            areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
            label_opts=opts.LabelOpts(is_show=True, position="top"),
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(title="Stacking area map"),
            tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"),
            yaxis_opts=opts.AxisOpts(
                type_="value",
                axistick_opts=opts.AxisTickOpts(is_show=True),
                splitline_opts=opts.SplitLineOpts(is_show=True),
            ),
            xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False),
        )
    
    )
    # ********** End **********#
    return line
 
make_snapshot(snapshot, line_chart().render("Result/render.html"), 'StudentAnswer/student_answer.png') # Output picture
make_snapshot(snapshot, line_stacked_area(x_data, y_data_1, y_data_2, y_data_3, y_data_4, y_data_5).render(), "StandardAnswer/task8/standard_answer_8.png")

Tags: Python Data Analysis data visualization echarts

Posted on Mon, 22 Nov 2021 23:23:16 -0500 by tomash