데이터 시각화: plotly를 사용하여perl에서 도표를 만듭니다.js (차트: Plotly)

내 글에서 나는 내가 더 많이 이야기할 것이라고 언급했다. Chart::Plotly오늘이 그날이야.따라서 더 이상 번거로울 필요 없이 시작합시다.
Chart::Plotly에서 말한 바와 같이Chart:Plotly는 자바스크립트 라이브러리plotly.js를 사용하여perl 데이터에서 html/javascript 도표를 만드는 데 도움을 줍니다.결과는 당신이 가장 좋아하는 브라우저에서 볼 수 있는 파일입니다.이미지를 로컬에 저장하고 필요에 따라 사용할 수도 있습니다.
음모의js는 매우 강력합니다. 많은 기능과 다양한 도표를 제공합니다.그것은 d3.jsstack.gl 위에 세워졌다.이 도표들은 완전히 맞춤형으로 제작할 수 있다.모든 구성은 선언 형식(JSON)으로 제공할 수 있으며 나머지는 JSON이 담당합니다.모든 복잡성이 해결되었기 때문에 자바스크립트 전문가가 될 필요가 없습니다.많은 문서examples와 도움을 드릴 수 있습니다.그것은 또한 통계와 과학 도표를 지지한다.Chart::Plotly를 PDL와 함께 사용할 수도 있습니다.
자, 시작합시다.

데이터 구성 만들기


우리는 본문과 완전히 같은 예시를 사용하여 다중 접선도를 만들어 보려고 한다.
{
    "title": "Number of automobiles sold per day by manufacturer",
    "domainAxis": {
        "data": ["2020-04-15", "2020-04-16", "2020-04-17", "2020-04-18"],
        "label": "Date"
    },
    "rangeAxis": {
        "lines": {
            "line1": {
                "data": [10,3,5,9],
                "legendName": "Honda"
            },
            "line2": {
                "data": [20,15,8,10],
                "legendName": "Toyota"
            },
            "line3": {
                "data": [6,19,12,4],
                "legendName": "Ford"
            },
            "line4": {
                "data": [16,10,6,12],
                "legendName": "Renault"
            }
        },
        "label": "Numbers of automobiles sold"
    }
}
이것은 다중 선형 그래프 데이터를 포함하는 설정입니다.domainAxis(x축)는 날짜축이고 rangeAxis(y축)는 4개의 선이 있다.

디렉토리 구조


우리의 디렉터리 구조는 매우 간단할 것이다.입력은 데이터를 입력하는 데 사용되고 출력은 도표를 만드는 데 사용되며 라이브러리는perl 모듈에 사용됩니다.
┣ 📂입력
┃ ┗ 📜데이터를 입력하다.json
┣ 📂해방당
┃ ┗ 📜선 그래프를 작성합니다.오후.
┣ 📂출력
┣ 📜다선도.pl
┗ 📜자술하다.의학 박사

모듈 만들기


이 모듈의 장점 중 하나는 plotly의 문서입니다.js는 여기서도 똑같이 적용된다.따라서 도표::플로리에 있는 문서도 적고 플로리에 있는 문서도 적다.js를 사용하면 퍼블릭 코드에서 똑같은 이름과 키워드를 사용할 수 있으며 문제가 발생하지 않습니다.또한 유사한 예는python 버전에서plotly에서도 찾을 수 있습니다.js 사이트.그래서 만약 당신이 이 세 가지 언어 중 어느 하나에 대해서도 조금은 알고 있다면 다른 언어에서 이것은 당신에게 지름길이다.
그럼 우리 모듈을 만듭시다.
package CreateLineCharts;
use strict;
use warnings;

# https://plotly.com/javascript/line-charts/
use Chart::Plotly 'show_plot';
use Chart::Plotly::Image 'save_image';
use Chart::Plotly::Plot;
use Chart::Plotly::Trace::Scatter;

sub generate_line_chart {
    my ($self, $chart_out_file, $chart_data) = @_;

    my $x_axis = $chart_data->{domainAxis};
    my $y_axis = $chart_data->{rangeAxis};

    my $plot = Chart::Plotly::Plot->new();
    foreach my $y_line (keys %{$y_axis->{lines}}) {
        my $scatter = Chart::Plotly::Trace::Scatter->new(
            x    => $x_axis->{data},
            y    => $y_axis->{lines}->{$y_line}->{data},
            name => $y_axis->{lines}->{$y_line}->{legendName}
         );
        $plot->add_trace($scatter);
    }

    # Opens the plot or plots in a browser locally
    show_plot($plot);

    # https://metacpan.org/pod/Chart::Plotly::Image#save_image
    save_image(
        file   => $chart_out_file,        # Referring to a local filesystem path
        plot   => $plot,
        width  => 1024,                   # Sets the image width
        height => 768,                    # Sets the image height
        engine => 'auto'
    );
}
여기서 우리는 줄마다 훑어보고 Chart::Plotly::Trace::Scatter 대상을 만들어서 드로잉에 추가할 뿐입니다.
두 가지 기능을 짚고 싶은데-
  • show_plot 함수는 사용자가 가장 좋아하는 브라우저에서 생성된 도표를 로컬로 열 것입니다.
  • save_image 생성된 파일이 로컬 파일 시스템에 로컬로 저장됩니다.이것은 자동으로 그것을 메일 첨부 파일로 보내려고 할 때 매우 유용할 것입니다.
    당신은 자신의 요구에 따라 그 중 어느 하나를 사용할 수도 있고, 이 두 가지를 동시에 사용할 수도 있습니다.
  • 모듈 사용


    이 모듈에 접근해서 도표를 만들기 위해 시작 스크립트를 만듭니다.
    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    use Cwd qw( abs_path );
    use File::Basename qw( dirname );
    use JSON;
    
    BEGIN {
        $ENV{"SCRIPT_DIR"} = dirname(abs_path($0));
    }
    
    use lib $ENV{"SCRIPT_DIR"} . "/lib";
    use CreateLineCharts;
    
    my $chart_out_file = $ENV{"SCRIPT_DIR"} . "/output/lineChart.png";
    
    sub read_json_file {
        my ($json_file) = @_;
        print "\nReading $json_file\n";
    
        open(my $in, '<', $json_file) or print "Unable to open file $json_file : $!";
        my $json_text = do { local $/ = undef; <$in>; };
        close($in) or print "\nUnable to close file : $!";
    
        my $config_data = decode_json($json_text);
        return $config_data;
    }
    
    
    sub main {
        my $data_in_json = read_json_file($ENV{"SCRIPT_DIR"} . "/input/input_data.json");
    
        my $chart = CreateLineCharts->new();
        $chart->generate_line_chart($chart_out_file, $data_in_json);
    
    }
    
    main;
    
    입력 파일에서 JSON 데이터를 읽고 모듈의generate line chart를 호출하고 있습니다.

    스크립트 실행


    현재 위의 스크립트를 실행하고 출력을 보기만 하면 됩니다.스크립트를 실행하면 가장 좋아하는 브라우저와 그래프를 자동으로 열 수 있습니다.출력은 두 위치에서 생성됩니다.
  • 브라우저에서

  • 로컬 output 디렉토리

    둘 다 비슷한 도표다.물론 브라우저는 동적 상호작용 도표이고 로컬 파일 시스템은 정적이다.
    브라우저에서 그래프 위에 마우스를 올려 놓을 때, 다른 몇 가지 옵션을 사용할 수 있습니다.오른쪽 위 모서리에 노란색으로 강조 표시된 상태로 표시됩니다.
  • 이렇게너는 코드가 가장 적은 다중 접선도를 가지고 있다.많은 설정 옵션을 사용할 수 있습니다.기본적으로 생성된 도표는 충분합니다.더 많은 옵션에 관심이 있다면 계속 진행하십시오.
    보상 - 브라우저의 URL을 발견하면 볼 수 있습니다.html 파일은 임시 위치에서 만듭니다.이 위치로 이동해서 가장 좋아하는 편집기에서 파일을 열려고 시도하십시오. (또는 요소를 검사해서 그곳에서 볼 수 있습니다.)
    <!DOCTYPE html>
    <head>
    <meta charset="utf-8" />
    </head>
    <body>
    <div id="1ca037ff-8fd4-11eb-bd22-b212bed9e091"></div>
    <script src="https://cdn.plot.ly/plotly-1.52.2.min.js"></script>
    <script>
    Plotly.react(document.getElementById('1ca037ff-8fd4-11eb-bd22-b212bed9e091'),[{"y":[16,10,6,12],"x":["2020-04-15","2020-04-16","2020-04-17","2020-04-18"],"name":"Renault","type":"scatter"},{"x":["2020-04-15","2020-04-16","2020-04-17","2020-04-18"],"y":[20,15,8,10],"type":"scatter","name":"Toyota"},{"name":"Honda","type":"scatter","y":[10,3,5,9],"x":["2020-04-15","2020-04-16","2020-04-17","2020-04-18"]},{"x":["2020-04-15","2020-04-16","2020-04-17","2020-04-18"],"y":[6,19,12,4],"type":"scatter","name":"Ford"}]  );
    </script>
    </body>
    </html>
    
    위의 템플릿은 Chart::Plotlyhere로만 생성됩니다.매번div id가 무작위로 생성됩니다.그런 다음 Plotly.react를 사용하여 드로잉을 생성합니다.

    일부 고급 구성 옵션


    내가 앞서 상세히 언급한 바와 같다.js 기능이 강하고 높이 설정 가능합니다.이제 이 구성들을 살펴보겠습니다.
    기본 설정이 마음에 들지 않으면 필요에 따라 변경할 수 있습니다.이러한 구성에는 플롯 선의 스타일 설정, 배치 변경, 범례, 태그, 글꼴, 색상, 텍스트 및 원하는 내용이 포함됩니다.
    이제 모듈에 이 설정을 추가합니다.
    package CreateLineCharts;
    use strict;
    use warnings;
    
    # https://plotly.com/javascript/line-charts/
    use Chart::Plotly 'show_plot';
    use Chart::Plotly::Image 'save_image';
    use Chart::Plotly::Plot;
    use Chart::Plotly::Trace::Scatter;
    
    use HTML::Show;
    
    use JSON;
    use Data::Dumper;
    
    sub new {
        my ($class, @arguments) = @_;
        my $self = {@arguments};
        bless $self, $class;
        return $self;
    }
    
    sub _generate_plot_lines {
        my ($self, $plot, $x_line, $y_line) = @_;
    
        # https://metacpan.org/pod/Chart::Plotly::Trace::Scatter
        # https://plotly.com/javascript/reference/scatter/
        my $scatter = Chart::Plotly::Trace::Scatter->new(
            x    => $x_line->{data},
            y    => $y_line->{data},
            name => $y_line->{legendName},
    
            # mode => 'markers',                 # Add markers at data points instead of line
            marker => {
                symbol  => 'diamond',            # Default - circle
                size    => 8,                    # marker size(in px). Default - 6px
                opacity => 0.8,                  # Marker opacity (0-1)
                # color   => 'red'               # Sets the marker color
            },
            opacity => 0.8,
            # text => $x_line->{data}            # Extra text you want to show on mouse hover over all the data points.
    
            # https://metacpan.org/pod/Chart::Plotly::Trace::Scatter::Line
            line => {
                # width   => 3,                  # Width of line, Default: 2
                # color   => '#45b5c6',          # Color of the line
                shape     => "spline",           # Determines the line shape - one of("linear" | "spline" | "hv" | "vh" | "hvh" | "vhv"), Default: "linear"
                smoothing => 0.5,                # Used only if `shape` is set to "spline", Default: 1
                dash      => "solid",            # Dash style of line - ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot"). Default: "solid"
                simplify  => JSON::false,        # Simplifies lines by removing nearly-collinear points. Default: true
            }
        );
        return $scatter;
    }
    
    sub _add_layout {
        my ($self, $plot, $chart_title, $x_axis_title, $y_axis_title) = @_;
        $plot->layout(
            {
                title => $chart_title,
                # font  => {                          # Sets the global font
                #     family => "Open Sans",          # Default font - ""Open Sans", verdana, arial, sans-serif"
                #     size     => 14                  # default - 12px
                # },
                # https://plotly.com/javascript/legend/
                legend => {
                    # orientation => "h",             # Sets the orientation of the legend('v' or 'h'). Default - v(vertical)
                    # xanchor     => "left",          # Sets the legend's horizontal position anchor. "left", "center" or "right"
                    # yanchor     => "bottom",        # Sets the legend's vertical position anchor. "top", "middle" or "bottom"
                    # x           => 0,               # number between or equal to -2 and 3
                    #                                 # Sets the x position (in normalized coordinates) of the legend.
                    #                                 # Defaults to "1.02" for vertical legends and defaults to "0" for horizontal legends.
                    # y           => -0.1,            # number between or equal to -2 and 3
                    #                                 # Sets the y position (in normalized coordinates) of the legend.
                    #                                 # Defaults to "1" for vertical legends, defaults to "-0.1" for horizontal legends on graphs w/o range sliders and defaults to "1.1" for horizontal legends on graph with one or multiple range sliders.
    
                    bgcolor     => "#ffffff",         # Sets the legend background color . Defaults to `layout.paper_bgcolor`
                    bordercolor => "#333333",         # Sets the color of the border enclosing the legend . Default - #444
                    borderwidth => 1,                 # Sets the width (in px) of the border enclosing the legend. Default - 0
                    font => {                         # Sets the font used to text the legend items.
                        size  => 14,
                        color => "#000000"            # Black
                    },
                    # title => {                      # Sets the title of the legend. Default - ""
                    #     text => "Legend",
                    #     font => {size => 14, color => "black"},
                    #     side => "top"               # Location of legend's title with respect to the legend items
                    # }
                },
    
                # showlegend => JSON::false,                # Whether you want to display the legend on not. Default - true
                # https://plotly.com/javascript/axes/
                # https://plotly.com/javascript/tick-formatting/
                xaxis => {
                    title      => $x_axis_title,            # Text label for x-axis
                    type       => "-",                      # x-axis type
                    automargin => JSON::true,
                    linecolor  => "#333333",                # Sets color of X-axis line
                    # titlefont  => {color => '#0066ff'},   # Title font formating
                    # tickfont   => {color => '#0066ff'},
                    zeroline   => JSON::true,               # Show zero line or not
                    zerolinecolor => '#cccccc',             # Assign specific color to zero line
                    zerolinewidth => 4,
    
                    # showgrid => JSON::false               # Removes X-axis grid lines
                    # rangeslider => { visible => JSON::false },
                    # gridcolor   => '#bfbfbf',
                    # gridwidth   => 1,
                    # tickformat => "YYYY-MM-DD",           # d3-format specifier. If empty or "" plotly will attempt to guess format
                    # dtick       => 1                      # step in-between ticks
                },
                yaxis => {
                    title      => $y_axis_title,
                    tickformat => "",                       # d3-format specifier. If empty or "" plotly will attempt to guess format.
                    automargin => JSON::true,
                    linecolor  => "#333333",                # Sets color of Y-axis line
                    # titlefont  => {color => '#0066ff'},
                    # tickfont   => {color => '#0066ff'},
                    rangemode  => "tozero",                 # Forced to start from zero. Default - "normal"
                    automargin => JSON::true,
                    zeroline   => JSON::true,               # Show zero line or not
                    # showgrid => JSON::false               # Removes Y-axis grid lines
                    # side => "left",                       # Location of y-axis. "left" or "right"
                    # gridcolor => '#bfbfbf',               # Assign specific color to grid 
                    # gridwidth => 1,
                    # dtick => 1                            # step in-between ticks
                },
                paper_bgcolor => "#ffffff",                 # Sets the background color of the paper where the graph is drawn. Default - #FFF
                plot_bgcolor => "#ffffff",                  # Sets the background color of the plotting area in-between x and y axes.
                margin => {                                 # Default(in px): left(80), right(80), top(100), bottom(80)
                    'l' => 50,
                    'r' => 50,
                    't' => 50,
                    'b' => 50
                },
                width  => 1000,                             # Sets the plot's width. Default - 700px
                height => 750,                              # Sets the plot's height. Default - 450px
            }
        );
    }
    
    sub _add_config {
        my ($self, $plot) = @_;
        # https://plotly.com/javascript/configuration-options/
        my %config = (
            scrollZoom => JSON::true,                   # mousewheel or two-finger scroll zooms the plot
            editable   => JSON::true,                   # In editable mode, users can edit the chart title, axis labels and trace names in the legend
            # staticPlot => JSON::true,                 # Create a static chart
            toImageButtonOptions => {                   # Customize Download Plot Options
                format   => 'svg',                      # one of png, svg, jpeg, webp. Default - png
                filename => 'multi_line_chart',         # Default name - newplot
                height   => 550,
                width    => 800,
                scale    => 1                           # Multiply title/legend/axis/canvas sizes by this factor
            },
            # displayModeBar => JSON::true,             # Force The Modebar at top to Always Be Visible.
                                                        # By default, the modebar is only visible while the user is hovering over the chart.
                                                        # Making it 'false' will never Display The Modebar
            modeBarButtonsToRemove => ['sendDataToCloud'],          # Delete some buttons from the modebar
    
            showLink        => JSON::true,                          # Display the `Edit Chart` Link
            plotlyServerURL => "https://chart-studio.plotly.com",   # Here you can directly edit your chart in browser
            linkText        => 'Edit chart in chart studio',
    
            # locale        => 'fr',                    # Change the Default Locale.
                                                        # More info - https://github.com/plotly/plotly.js/blob/master/dist/README.md#to-include-localization
            displaylogo      => JSON::false,            # Hide the Plotly Logo on the Modebar
            # responsive     => JSON::true,             # Responsive to window size
            # doubleClickDelay => 1000,                 # maximum delay between two consecutive clicks to be interpreted as a double-click in ms (default 300 ms)
        );
        $plot->config(\%config);
    }
    
    sub generate_line_chart {
        my ($self, $chart_out_file, $chart_data) = @_;
    
        my $x_axis = $chart_data->{domainAxis};
        my $y_axis = $chart_data->{rangeAxis};
    
        my $plot = Chart::Plotly::Plot->new();
        foreach my $y_line (keys %{$y_axis->{lines}}) {
            my $scatter = $self->_generate_plot_lines($plot, $x_axis, $y_axis->{lines}->{$y_line});
            $plot->add_trace($scatter);
        }
    
        $self->_add_layout($plot, $chart_data->{title}, $x_axis->{label}, $y_axis->{label});
    
        $self->_add_config($plot);
    
        my $html = $plot->html(
            div_id => 'my_div_id',                          # Id of the div, in which you want your chart to be embedded
            load_plotly_using_script_tag => 'embed'         # Can be : 1 or cdn, embed, module_dist.
                                                            # * By default, it is 1(cdn) meaning it will load plotly.js using cdn link.
                                                            # * 'embed' will take it from the plotly.js that is shipped wth Chart::Plotly and paste it within <script> tag.
                                                            # * 'module_dist' is similar to 'embed' except it will provide the source in <script src="file://">.
                                                            # Please note that using 'module_dist' will show the actual location of the file on your location machine(e.g. /usr/lib/perl/5.30/site/lib/Chart-Plotly/plotly.js/plotly.min.js).
                                                            # So, beware of this as you will be showing this location in your browser
        );
    
        # Returns the structure suitable to serialize to JSON corresponding to the plot
        # print Dumper($plot->TO_JSON);
    
        # Returns the plot serialized in JSON . Not suitable to use in nested structures
        # print Dumper($plot->to_json_text);
    
        # Opens the plot or plots in a browser locally.
        # Both are equal. In second statement we are just updating the div id with user defined one and determining how to load plotly.js
        show_plot($plot);
        HTML::Show::show($html);
    
        # https://metacpan.org/pod/Chart::Plotly::Image#save_image
        save_image(
            file   => $chart_out_file,          # Referring to a local filesystem path
            format => "png",                    # Supported formats are png, jpeg, webp, svg, pdf, eps.
                                                # By default it's inferred from the specified file name extension
            scale => 1,                         # Multiply title/legend/axis/canvas sizes by this factor
            plot  => $plot,
            # width  => 1024,                   # Sets the image width
            # height => 768,                    # Sets the image height
            engine => 'auto'
        );
    }
    
    1;
    
    압도적인 거 알아요.그러나 나는 모든 설정의 기능을 이해하는 데 많은 시간을 썼다.나는 이 설정 옵션의 앞이나 끝에 도와 don을 주석으로 추가했다.
    나는 음모를 겪은 적이 있다.js 문서,perl 버전에서 시도했습니다.나를 놀라게 한 것은 그들 모두가 퍼블릭 세계에서 일하고 있다는 것이다.앞서 언급한 바와 같이Chart: Plotly의 문서는 개선할 수 있습니다. 이 예는 처음 사용하는 사람을 도울 수 있습니다.
    또한Chart:Plotlyexamples 부분을 보고 다양한 도표의 예시를 더 많이 알 수 있습니다.
    이제 출력을 다시 실행하고 봅시다.3개의 출력이 생성됩니다.두 개는 브라우저에 있고 하나는 로컬 디렉토리에 있습니다.
    나는 몇 가지 일을 지적하고 싶다.
  • show_plot($plot) - 브라우저의 첫 번째 출력은 여기서 생성됩니다.

  • HTML::Show::show($html) - 브라우저의 두 번째 출력은 여기서 생성됩니다.이 말은 첫마디와 비슷하지만 두 가지 다른 점이 있다.하나는 div_id 이고, 우리는 사용자 정의를 사용합니다.두 번째 문제는 어떻게 정성껏 계획하는가이다.js는 도표를 만드는 데 사용됩니다. (cdn이나chart:Plotly 등과 함께 제공하는 도표)원소를 검사하고, 이 점과 첫 번째 점 사이의 차이를 검사하면 알게 될 것이다.다음은'div'id가 사용자 정의이고 <script> 표시가plotly를 포함하는 것을 볼 수 있습니다.cdn 링크가 아닌 js를 삽입합니다.

  • save_image - 로컬에서 생성된 세 번째 도표는 이 함수에서 나온 것입니다.

  • $plot->TO_JSON - 드로잉에 해당하는 JSON으로 서열화하는 데 적합한 구조를 반환합니다.너는 그것을 거꾸로 해서 도표 안에서 도대체 무슨 일이 발생했는지 볼 수 있다.모든 설정과 설정 옵션을 볼 수 있습니다.
  • $plot->config(\%config) - 차트의 추가 구성이것은 주로 브라우저에서 볼 수 있는 특정한 도표입니다.
  • JSON::falseJSON::true - 퍼블릭 값이 없기 때문에, 자바스크립트의false나true로 설정 옵션을 설정합니다. 구체적으로javascript의false나true에 달려 있습니다.필요한 경우 다른 JSON 모듈을 사용하여 유사한 목적을 달성할 수 있습니다.
  • 앞에서 말한 바와 같이, 나는 다중 접선도만 만들었지만, 여러 가지 옵션을 사용할 수 있고, 각각의 옵션은 하나의 설정을 가지고 있다.너는 그 중에서 선택할 수 있다.
    나는 네가 이 모듈을 어떻게 사용하는지에 대해 좀 이해하기를 바란다.그래서 다음에 도표를 만들 기회가 생기면 뭘 써야 할지 알게 될 거예요.
    위의 예는 github에서도 사용할 수 있습니다.
    Perl 양파 로고here
    Plotly 로고 출처here
    표지의 도표 사진에서 추출here

    좋은 웹페이지 즐겨찾기