The mixed use of pyecharts and echarts

Echarts is a pure Javascript chart library developed by Baidu. Pyecharts is the product of three tycoons transplanting echarts into Python project. It is easier to access charts in Python website, but pyecharts is much more limited than echarts, pyechart 1. X version is even smaller, because pyechart 1.11.13 version is used before the project, as shown in Fig There are few tables, which is not enough to solve the problem. Even two charts are implemented by js, which is less beautiful than echarts. If you migrate the project to the new version of pyecharts 2. X, it is more troublesome. You can directly introduce echarts library into the original project for mixed use. Pyechart 2. X has improved many problems, but added new configuration rules to learn more After a lot of burden, the flexibility is not as good as echarts. I suggest that pyecharts can be used if the chart used in the project is not very complex, and pyecharts can be used if the data is static. It is more convenient to use echarts if the chart is complex. Let's start with the topic:

1. Install pyecharts:

sudo pip install Django==1.11.13 ා the old version of 1.x, which I currently use, it is recommended to install the latest version below if pyecharts is used
sudo pip install Django==2.1.5, the latest version of 19 years, you can install this

Sudo apt install Python 3-django

pyecharts can use charts to build charts directly in the view code. Django will render them to the front-end template page:

# Main body diagram-1
def visualPage(request):
    template = loader.get_template('visualModule/visualPage.html')  #Load template file
    
    parseArgData()
    
    data3D1,weights3D1,bar = drawBar() #Get chart data
    context = dict(     #context Add data to render in the template
        myechart = bar.render_embed(),  #Chart data
        host = DEFAULT_HOST,
        script_list = bar.get_js_dependencies(),  #Introduction of js code file needed by pyecharts
        guestSetArgs=startArgsSet,
        warningdata=argList,
        data3D=data3D1,
        weights3D=weights3D1,
    )
    return HttpResponse(template.render(context, request))#

To build the chart function, only the interface code of the chart is pasted here, and the data processing and logic code are omitted:

def drawBar(): #Draw
        x_axis = ['','','','','','','','','','','',''] #X axis
        y_axis = [0,1,2,3,4,5,6,7,8,9,10,11]

    
        data = [
        #Closed source 5
        dict(
        name = "",
        value=[so[0], sor[0], projects[0][0][""]],
        itemStyle=dict(color=getColorstr2(0,weights[0]))
        ),

        dict(
        name="",
        value=[so[4], sor4[2], projects[4][2][""]],
        itemStyle=dict(color=getColorstr2(4,weights[18]))
        ),

        ...
        ]
        bar3d = Bar3D("", width=1000, height=500)
        bar3d.add("",x_axis,y_axis, data,
        is_visualmap=False,
        is_xaxis_show=True,
        is_yaxis_show=False,
        is_splitline_show=False,
        xaxis3d_name =' ',
        yaxis3d_name =' ',

        #is_label_show =True,
        mark_point_symbol='circle',
        is_more_utils=True,
        mark_point=['max','min'],
        mark_line=['average'],

        zaxis3d_name ='score',
        xaxis3d_interval =0,
        grid3d_width=150, grid3d_depth=100,
        grid3d_shading='realistic',
        is_grid3d_ratate = True,
        grid3d_rotate_speed=180,
        tooltip_formatter=formatter)

        bar3d.on(MOUSE_CLICK, on_click)
        return data,weights,bar3d

So you can display the bar chart at the front

 

 

 

In addition, a line chart is also used in the project

 

 

 

Other charts are also added similarly. Please refer to the pyecharts official website tutorial:

https://pyecharts.org/#/

2. Next, we will introduce echarts to the project, which will not affect each other when mixed with pyecharts

For installation, please refer to the official website of echarts:

https://www.echartsjs.com/zh/

Go to https://github.com/apache/incubator-echarts to download the echarts source package. You can find the latest version of the echarts Library in the dist directory in the extracted folder. You can directly import it into the front page to use the echarts chart,

1 {% for jsfile_name in script_list %}
2         <script src="{{ host }}/{{ jsfile_name }}.js"></script>
3     {% endfor %}
4     
5          <script src="{% static 'js/dist/echarts.min.js' %}"></script>
6      <script src="{% static 'js/dist/echarts-gl.js' %}"></script>
 <div id="container3" style="height: 800px"></div>
    
       <script type="text/javascript">
       //echarts Histogram
var dom3 = document.getElementById("container3");
var myChart3 = echarts.init(dom3);
var app = {};
option = null;

var hours = [];
var days = [];

$.get("{% static 'json/eachBar3dData.json' %}",function (json_data) {
    var jdata=[];
    $(json_data.items).each(function(i,ite){  
        jdata.push(ite)
    })
    rectSize=Math.sqrt(json_data.length);
    for(var i=0;i<rectSize;i++)
    {
        hours.push('');
        days.push('');
    }    
    option = {
        title: {
            text: 'Number of codes of all code sub modules 3 D Histogram',
            subtext: 'Number of codes and defects can be displayed',
            left: 'leafDepth'
        },
        tooltip: {
            formatter:function(params)
                {
                   var errors=0;
                   for(var i =0;i< json_data.length;i++)
                   {
                        if (json_data[i][3]==params.name)
                        {
                            errors=json_data[i][4];
                            break;
                        }
                   }
                   return "<div >"+"File path:"+params.name+'<br>'+
                  "Lines of code:"+params.value[2]+'<br>'+
                  "Number of defects:"+errors+
                   "</div>";
                }, 
        },
        visualMap: {
            max: 4000,
            inRange: {
                color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
            }
        },
        xAxis3D: {
            type: 'category',
            data: hours,
            name: ''
        },
        yAxis3D: {
            type: 'category',
            data: days,
            name:''
        },
        zAxis3D: {
            type: 'value',
            name:'Code quantity'
        },
        grid3D: {
            boxWidth: 200,
            boxDepth: 180,
            viewControl: {
                // projection: 'orthographic'
            },
            light: {
                main: {
                    intensity: 1.2,
                    shadow: true
                },
                ambient: {
                    intensity: 0.3
                }
            }
        },
       /* dataset: {
            dimensions: [
                'Income',
                'Life Expectancy',
                'Population',
                'Country',
                {name: 'Year', type: 'ordinal'}
            ],
            source: json_data
        },
        */
        series: [{
            type: 'bar3D',
            data: json_data.map(function (item) {
                return {
                    name:item[3],
                    value: [item[1], item[0], item[2]],
                }
            }),
            shading: 'lambert',

            label: {
                textStyle: {
                    fontSize: 16,
                    borderWidth: 0
                }
            },

            emphasis: {
                label: {
                    textStyle: {
                        fontSize: 20,
                        color: '#900'
                    }
                },
                itemStyle: {
                    color: '#900'
                }
            }
        }]
    };
    myChart3.setOption(option, true);
}); 
if (option && typeof option === "object") {
    myChart3.setOption(option, true);
}
       </script>  
       
       
           
    </div>         

Display effect:

 

 

 

 

In addition, tree chart is also used in the project to represent the file directory structure:

 

 

Drillable rectangular tree:

 

 

 

 

Because this chart does not exist in pyecharts1.x, pyecharts2.x and echarts2. X are not added, or I haven't looked at it carefully or found it, so I implemented a similar drill in tree chart

 

At the same time, in order to practice, I also realized a bar chart:

 

 

The number and shape of graphics are adapted according to the change of data, but the beauty is much worse than that of eckarts

3. Use of echarts event interaction

When a radar chart is used in the project, you need to click the note to enter the sub chart of the note, which is also a similar drill in chart. There are many logic codes, and some logic codes in GETOPTION (argname) function are omitted:

 <div id="container" style="height: 800px"></div>
    
       <script type="text/javascript">
var dom = document.getElementById("container");
var myChart = echarts.init(dom);
var app = {};
var weight=1000; //Multiple of weight
var weight1=800;
function getOption( argName){
    var ardData=[];

    if(argName=="Closed source characteristics"){ //Judge click text
       var weightBuf= [{{weights3D.0}},{{weights3D.1}},{{weights3D.2}},{{weights3D.3}},{{weights3D.4}},
                        ];
                        
        var weightBuf1=[];
        weightBuf.forEach(myFunction);    
        function myFunction(value, index, array) {
          weightBuf1.push(value*weight1); 
        }
           ardData=[
                    {
                        value : [{{data3D.0.value.2}},{{data3D.1.value.2}},{{data3D.2.value.2}},{{data3D.3.value.2}},{{data3D.4.value.2}}, 
                       ],
                        name : 'score'
                    },
                     {
                        value : weightBuf1,
                        name : 'weight'
                    }
                ];
        option = null;
        option = {
            title: {
                text: 'Radar chart',
                subtext: 'Click the text element to return to the top attribute radar chart',
            },
            tooltip: {
                formatter:function(params)
                {
                    namelist=['Correctness', 'reliability', 'Safety', 'Comprehensibility','Code entropy']
                    var eachli=params.value;
                    if (params.name=='weight')
                    eachli=weightBuf;
                     return "<div >"+params.name+'<br>'+
                    namelist[0]+': '+eachli[0]+'<br>'+
                   namelist[1]+': '+eachli[1]+'<br>'+
                   namelist[2]+': '+eachli[2]+'<br>'+
                   namelist[3]+': '+eachli[3]+'<br>'+
                   namelist[4]+': '+eachli[4]+
                   "</div>";
                }, 
            },
            legend: {
                data: ['Score ( scole)', 'Weight ( weight)']
            },
            radar: {
                // shape: 'circle',
                name: {
                    textStyle: {
                        color: '#000',
                        backgroundColor: '#dee',
                        borderRadius: 3,
                        padding: [3, 5]
                   }
                }, 
                indicator: [
                   { name: 'Correctness', max: 100},
                   { name: 'reliability', max: 100},
                   { name: 'Safety', max: 100},
                   { name: 'Comprehensibility', max: 100},
                   { name: 'Code entropy', max: 100},
                ],
                triggerEvent:true
            },
            
            series: [{
                name: 'score vs weight',
                type: 'radar',
                // areaStyle: {normal: {}},
                data : ardData
            }]
        };;
    }
 return option;
}
option=getOption("root");
if (option && typeof option === "object") {
    myChart.setOption(option, true);
    
    
      myChart.on('click', function (params) {
        console.log(params);
       // alert(params.name);
        myChart.setOption(getOption(params.name), true);
     });

}
       </script>     
       

Mainly used

 myChart.on('click', function (params) {
        console.log(params);
       // alert(params.name);
        myChart.setOption(getOption(params.name), true);
     });
To monitor the mouse click tag event, and then dynamically build the option display through getOption to achieve the drill in effect

Drill in effect after clicking

 

 

4. Customize the toolip label

Define formatter in toolip, params parameter is the element data of current activity

tooltip: {
            formatter:function(params)
                {
                   var errors=0;
                   for(var i =0;i< json_data.length;i++)
                   {
                        if (json_data[i][3]==params.name)
                        {
                            errors=json_data[i][4];
                            break;
                        }
                   }
                   return "<div >"+"File path:"+params.name+'<br>'+
                  "Lines of code:"+params.value[2]+'<br>'+
                  "Number of defects:"+errors+
                   "</div>";
                }, 
        },

Effect:

 

 

The prompt box floating content formatter supports two forms: String template and callback function.

1. String template

Template variables are {a}, {b}, {c}, {d}, {e}, respectively, representing series name, data name, data value, etc In trigger When 'axis' is selected, there will be multiple series of data. At this time, the index of the series can be represented by {a0}, {a1}, and {a2} The meanings of {a}, {b}, {c}, {d} are different under different chart types Among them, variables {a}, {b}, {c}, {d} represent data under different chart types

  • Line (area), column (bar), K-line: {a} (series name), {b} (category value), {c} (value), {d} (none)

  • Scatter (bubble) chart: {a} (series name), {b} (data name), {c} (numeric array), {d} (none)

  • Map: {a} (series name), {b} (region name), {c} (combined value), {d} (none)

  • Pie, dashboard, funnel: {a} (family name), {b} (data item name), {c} (value), {d} (percentage)

For more information about the meaning of other chart template variables, see the corresponding chart's label.formatter configuration item.

Example:

formatter: '{b0}: {c0}<br />{b1}: {c1}'

2. Callback function

Callback function format:

(params: Object|Array, ticket: string, callback: (ticket: string, html: string)) => string

The first parameter, params, is the data set required by formatter. The format is as follows:

{
    componentType: 'series',
    //Series type
    seriesType: string,
    //index of series in the incoming option.series
    seriesIndex: number,
    //Series name
    seriesName: string,
    //Data name
    name: string,
    //index of data in the data array passed in
    dataIndex: number,
    //Incoming raw data item
    data: Object,
    //The data value passed in. It's the same as data in most series. In some series, the components in data (such as map and radar)
    value: number|Array|Object,
    //Coordinate axis encode mapping information,
    //key is the coordinate axis (such as' x 'y' radius' angle ')
    //value must be an array, not null/undefied, indicating dimension index.
    //The contents are as follows:
    // {
    //X: [2] / / the data with dimension index 2 is mapped to the x-axis
    //Y: [0] / / data with dimension index 0 is mapped to y-axis
    // }
    encode: Object,
    //Dimension name list
    dimensionNames: Array<String>,
    //Dimension index of data, such as 0 or 1 or 2
    //Use only in radar maps.
    dimensionIndex: number,
    //Color of data graphics
    color: string,

    //Percentage of pie chart
    percent: number,

}

The callback function I use here is more convenient to define radar chart
For more information, please refer to the official documentation tutorial:
https://www.echartsjs.com/zh/option.html#title

Tags: Javascript Django Python sudo

Posted on Tue, 05 Nov 2019 01:45:47 -0800 by kingman65