파이톤과 같은 문법으로 사용할 수 있는 Plattly의 Juria 인터페이스를 만들었다.

오늘


PyPlotly.jl
... 면

배경 만들기


상호작용을 잘하는 도표 그리기 라이브러리가 있습니다.홈페이지에서 대시보드를 만드는 애플리케이션Plotly에서는 도표를 그릴 때 진귀한 보물로 여겨진다.
JS(=JavaScript)는 당연히 Pyhon, R, Juria 등 각종 인터페이스를 지원한다.

근거Dash
기능을 사용할 수 있습니다.
# https://plotly.com/julia/2d-histogram-contour/ から抜粋
using PlotlyJS, Distributions

x = rand(Uniform(-1,1), 500)
y = rand(Uniform(-1,1), 500)

plot(histogram2dcontour(
        x = x,
        y = y,
        colorscale = "Jet",
        contours = attr(
            showlabels = true,
            labelfont = attr(
                family = "Raleway",
                color = "white"
            )
        ),
        hoverlabel = attr(
            bgcolor = "white",
            bordercolor = "black",
            font = attr(
                family = "Raleway",
                color = "black"
            )
        )

))
내부는 JS의 API에 직접 접근하기 위해 매우 비슷하게 쓸 수 있다.
// https://plotly.com/javascript/2d-histogram-contour/#styled-2d-histogram-contour から抜粋
var x = [];
var y = [];
for (var i = 0; i < 500; i ++) {
	x[i] = Math.random();
	y[i] = Math.random() + 1;
}

var data = [
  {
    x: x,
    y: y,
    colorscale: 'Blues',
    type: 'histogram2dcontour',
    contours: {
      showlabels: true,
      labelfont: {
        family: 'Raleway',
        color: 'white'
      }
    },
    hoverlabel: {
      bgcolor: 'white',
      bordercolor: 'black',
      font: {
        family: 'Raleway',
        color: 'black'
      }
    }
  }
];
Plotly.newPlot('myDiv', data);
다른 한편, 파이톤이라면 어떨까?
# https://plotly.com/python/2d-histogram-contour/ から抜粋
import plotly.graph_objects as go

import numpy as np

x = np.random.uniform(-1, 1, size=500)
y = np.random.uniform(-1, 1, size=500)

fig = go.Figure(go.Histogram2dContour(
        x = x,
        y = y,
        colorscale = 'Jet',
        contours = dict(
            showlabels = True,
            labelfont = dict(
                family = 'Raleway',
                color = 'white'
            )
        ),
        hoverlabel = dict(
            bgcolor = 'white',
            bordercolor = 'black',
            font = dict(
                family = 'Raleway',
                color = 'black'
            )
        )

))

fig.show()
대체적으로 비슷하지만 사용go = plotly.graph_objects이나 2차원 직사각형의 이름은 파이톤 코드 규약을 따르는 upper camel case이다.또한 plotly.express 독립된 모듈 인터페이스를 가지고 있다.
닭 vs. 달걀과 마찬가지로 프로그래머가 처음 배운 언어는 파이톤이다. API를 자연스럽게 볼 수 있다면 JS 측의 쥬리아 측이 독특해진다.그리고 plotly로 검색하면 파이톤의 사용 방법이 흔한 경우가 많습니다.
자신도 파이톤을 주로 사용하는데 파이톤이 쓴 것을 JS에 가져가는 작법이 좀 힘들다.이 반은 JS/Juria로 어떻게 씁니까?API 참고서를 뚫어지게 쳐다볼 필요가 있다. 구글이라도 한꺼번에 걸리지 않는다(^^;)

그렇기 때문에


그래서 파이토존에서 주리아로 옮길 때도 이런 문제가 있었어요. 이 문제를 해결하기 위해서.
했어PlotlyJS.jl.
이름PyPlotly은 플랜틀리다.이미 jl가 있으니까.이것은
Plotting functions provided by this package are identical to PlotlyJS. Please consult its documentation. In fact, the package depends on PlotlyJS.jl and reexports all the methods.
플레이티를 위한 클라우드 서비스의 API에 대한 것

사용법


지금은 밭포장으로 수동dd나 복제가 필요합니다.
$ pip3 install numpy pandas plotly
$ git clone https://github.com/AtelierArith/PyPlotly.jl.git
$ cd PyPlotly
$ julia --project=@. -e 'using Pkg; Pkg.isinstance()'
코드는 다음과 같다.
using PyPlotly # これをすると `go`, `px` が使える 
go.Figure(
    go.Histogram2dContour(
        x = x,
        y = y,
        colorscale = "Jet",
        contours = Dict(
            :showlabels => true,
            :labelfont => Dict(:family => "Raleway", :color => "white"),
        ),
        hoverlabel = Dict(a)
    ),
)

나는 네가 그것이 파이톤의 작법과 비슷하다는 것을 발견할 수 있을 것이라고 생각한다.Dict의 부분을 조절해야 하지만 대체로 기계적으로 변환할 수 있다.
README에 적힌 예라면 기본적으로 같은 글씨를 쓸 수 있다는 것을 알 수 있을 것이다.
# これは Python
import plotly.graph_objects as go

# Create random data with numpy
import numpy as np
np.random.seed(1)

N = 100
random_x = np.linspace(0, 1, N)
random_y0 = np.random.randn(N) + 5
random_y1 = np.random.randn(N)
random_y2 = np.random.randn(N) - 5

fig = go.Figure()

# Add traces
fig.add_trace(go.Scatter(x=random_x, y=random_y0,
                    mode='markers',
                    name='markers'))
fig.add_trace(go.Scatter(x=random_x, y=random_y1,
                    mode='lines+markers',
                    name='lines+markers'))
fig.add_trace(go.Scatter(x=random_x, y=random_y2,
                    mode='lines',
                    name='lines'))

fig.show()
# こっちは Julia
using PyPlotly # this exports `go` and `px`

using Random
Random.seed!(1)

N = 100
random_x = range(0, 1, length=N)
random_y0 = randn(N) .+ 5
random_y1 = randn(N)
random_y2 = randn(N) .- 5

fig = go.Figure()

# Add traces
fig.add_trace(go.Scatter(x=random_x, y=random_y0,
                    mode="markers",
                    name="markers"))
fig.add_trace(go.Scatter(x=random_x, y=random_y1,
                    mode="lines+markers",
                    name="lines+markers"))
fig.add_trace(go.Scatter(x=random_x, y=random_y2,
                    mode="lines",
                    name="lines"))

fig
px(=plotly.express)의 예에 따르면 복사하고 붙이기만 하면 파이톤<->Juria의 변환은 즉시 대응할 수 있습니다.
# using PyPlotly <--- Julia
# import plotly.express as px <--- Python

df = px.data.iris()
fig = px.scatter(
    df,
    x="sepal_width",
    y="sepal_length",
    color="species",
    size="petal_length",
    hover_data=["petal_width"],
)
fig

동작의 원리는 며칠 전에 설명한 것과 같다PyPlotly.jl.
이 기사가 나오기 이틀 전부터 개발된 것은 PyPlattly다.jl의 메이킹 애니메이션을 찍었습니다.이후 버그가 발견됐는데 기능을 확장하기 위한 시행 오류가 좀 이상했지만 애니메이션에 포함된 실제 모습과 같은 생각이었다.

PlotlyJS.jl로 변환


다음 변환 함수를 만들면 됩니다.jl에서도 사용하고 있어요.
function create_plotlyjs(fig::GraphObjects.Figure)
    jsonobj = JSON.parse(fig.to_json())
    traces = PlotlyJS.GenericTrace.(jsonobj["data"])
    layout = PlotlyJS.Layout(jsonobj["layout"])
    return PlotlyJS.plot(traces, layout)
end
여기서 IJulia 등에 그릴 때 PlatlyJS.jl의 display 함수를 사용하여 스스로 실현할 필요가 없게 할 수 있다.

총결산


파이썬 이용자들에게 부드러운 줄리아에서 플래틀리를 사용하는 방법을 소개했다.

좋은 웹페이지 즐겨찾기