React アプリで Plotly Charting ライブラリを使用する方法
D3 と stack.gl 上に構築されるデータ サイエンティスト向けのグラフ作成ライブラリ
序章
Plotlyは、ケベック州モントリオールに本社を置くコンピューティング会社で、オンライン データ分析および視覚化ツールを開発しています。個人向けのオンライン グラフ作成、分析、統計ツールと、Python、 R、MATLAB、Perl、Julia、Arduino、REST用のコラボレーションおよび科学グラフ作成ライブラリを提供します。Plotly ツールを使用して、Jupyter Notebook でインタラクティブなグラフのスタイルを設定することもできます。
Plotlyは商品名でもあります。Plotly.js は、モジュール式 WebGL コンポーネントであるD3およびstack.gl上に構築されるグラフ作成ライブラリです。これは高レベルの宣言型グラフ作成ライブラリであり、3D、統計、科学、財務、SVG マップを含む 40 種類を超えるグラフ タイプが付属しています。Plotly は、JavaScript ライブラリのほかに、plotly.pyおよびLotly.Rも強化します。Plotly チャートは、 MLflow、Hugging Face の Point-E デモなど、AI/データ サイエンス コミュニティで広く採用されています。
Plotly がどのように機能するかを見てみましょう。
React アプリの作成で Plotly.js をセットアップする
私たちは、plotly.js を探索するためのベースとしてCreate React Appを使用します。次のコマンドは React プロジェクトを作成します。
% yarn create react-app react-plotly
% cd react-plotly
% yarn add plotly.js react-plotly.js
"dependencies": {
"plotly.js": "^2.17.0",
"react-plotly.js": "^2.6.0"
}
棒グラフ
棒グラフは、カテゴリデータを、それらが表す値に比例した高さまたは長さの長方形の棒で表します。バーは垂直または水平にプロットできます。縦棒グラフは、縦棒グラフと呼ばれることもあります。
Plotly では、一連のデータはトレースの配列で構成されます。各トレース オブジェクトはtype、x、 、y、およびその他の情報で構成されます。
xx値の連続的な配列である座標を設定します。デフォルト値は、0 から始まり 1 ずつ増加するシーケンスです。yyは、 の各点の値の配列である座標を設定しますy。- 棒グラフの種類は です
'bar'。
title3 ~ 7 行目で、 、width、およびを使用してレイアウト オブジェクトを作成しますheight。- 9 ~ 18 行目で、2 つのトレース オブジェクトで構成されるデータ配列を作成します。
'bar'どちらのトレースも、値とともに のタイプとして定義されますy。 - 21 行目で棒グラフが作成されます。
次のコードを使用して、バーの 1 つを水平方向に変更できます。
const dataArray = [
{
type: 'bar',
y: [1, 2, 1, 4, 3, 6],
orientation: 'h',
},
{
type: 'bar',
y: [2, 7, 0, 4, 6, 2],
},
];
混合方向はデモンストレーションのみを目的としています。おそらく、実際の使用例では、すべてのバーが同じ方向を向いています。
次のコードを使用して、両方のバーを水平方向に設定します。
const dataArray = [
{
type: 'bar',
y: [1, 2, 1, 4, 3, 6],
orientation: 'h',
},
{
type: 'bar',
y: [2, 7, 0, 4, 6, 2],
orientation: 'h',
},
];
散布図
A line chart connects a series of data points using a line, and a scatter chart displays a collection of points. In Plotly, both line and scatter charts have the type of 'scatter'. It uses mode to determine the drawing mode:
'lines': It draws a line plot.'markers': It draws a scatter plot.'text': It displays a text.'none': It displays nothing.
Here is the modified src/App.js:
- At lines 3–7, it creates a layout object, with
title,width, andheight. - At lines 9–20, it creates a data array composed of two trace objects. Both traces are defined as type of
'scatter', along withyvalues. The first trace setsmodeto'lines', and the second setsmodeto'markers'. - At line 23, the scatter chart is created.
Here is the modified src/App.js that uses combined modes.
- At lines 3–7, it creates a layout object, with
title,width, andheight. - At lines 9–28, it creates a data array composed of two trace objects.
– At lines 10–14, the first trace sets the mode to'lines+markers'.
– At lines 15–26, the second traces set the mode to'markers+lines'. In addition, it setsmarker.colorto'green',marker.sizeto 12,line.colorto'red', andline.widthto 3. - At line 31, the scatter chart is created.
The following dataArray adds text to mode for both traces, along with an array of text values. Here’s the code:
const dataArray = [
{
type: 'scatter',
y: [1, 2, 1, 4, 3, 6],
mode: 'lines+markers+text',
text: ['Line1-a', 'Line1-b', 'Line1-c', 'Line1-d', 'Line1-e', 'Line1-f'],
},
{
type: 'scatter',
y: [2, 7, 0, 4, 6, 2],
mode: 'text+markers+lines',
text: ['Line2-a', 'Line2-b', 'Line2-c', 'Line2-d', 'Line2-e', 'Line2-f'],
marker: {
color: 'green',
size: 12,
},
line: {
color: 'red',
width: 3,
},
},
];
It works, except that there are some overlaps between markers and text.
We can shift the text positions to avoid overlaps:
const dataArray = [
{
type: 'scatter',
y: [1, 2, 1, 4, 3, 6],
mode: 'lines+markers+text',
text: ['Line1-a', 'Line1-b', 'Line1-c', 'Line1-d', 'Line1-e', 'Line1-f'],
textposition: 'top center',
},
{
type: 'scatter',
y: [2, 7, 0, 4, 6, 2],
mode: 'text+markers+lines',
text: ['Line2-a', 'Line2-b', 'Line2-c', 'Line2-d', 'Line2-e', 'Line2-f'],
textposition: 'bottom center',
marker: {
color: 'green',
size: 12,
},
line: {
color: 'red',
width: 3,
},
},
];
We have seen x and y dimensions in a Plotly chart, and there is another dimension, the color dimension, in scatter charts. In the following example, we create a chart with seven horizontal scatter traces with markers. These markers are used to explain how color dimension works.
Here is our target chart:
And here is the modified src/App.js:
- At lines 10–18,
trace 0definesyvalues to be[6, 6, 6, 6, 6, 6](line 12), andmarker.colorto be a simple color,'red'(line 15). - At lines 19–28,
trace 1definesyvalues to be[5, 5, 5, 5, 5, 5](line 21), andmarker.colorscaleto be[[0, 'green'], [1, 'blue']](line 24).colorscaleis an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required.colorscalehas an effect only ifmarker.coloris set to a numerical array (line 25). - At lines 29–39,
trace 2definesyvalues to be[4, 4, 4, 4, 4, 4](line 31). Sincemarker.colorscaleis not defined, the defaultcolorscaleis applied.marker.cmin(line 35) sets the lower bound of the color domain, andmarker.cmax(line 36) sets the upper bound of the color domain. Otherwise,marker.cminandmarker.cmaxwill be deducted frommarker.color(line 34). - At lines 40–49,
trace 3definesyvalues to be[3, 3, 3, 3, 3, 3](line 42).marker.cmid(line 46) sets the mid-point of the color domain by scalingmarker.cminand/ormarker.cmaxto be equidistant to this point. - At lines 50–59,
trace 4definesyvalues to be[2, 2, 2, 2, 2, 2](line 52). Besides definingcolorscale, we can use a predefined palette name from the list:'Blackbody','Bluered','Blues','Cividis','Earth','Electric','Greens','Greys','Hot','Jet','Picnic','Portland','Rainbow','RdBu','Reds','Viridis','YlGnBu', and'YlOrRd'. Fortrace 4,marker.colorscaleis set to'Greens'(line 56). - At lines 60–69,
trace 5definesyvalues to be[1, 1, 1, 1, 1, 1](line 62), andmarker.colorscaleto be'YlOrRd'(yellow or red, line 66). - At lines 70–85,
trace 6definesyvalues to be[0, 0, 0, 0, 0, 0](line 72), andmarker.colorscaleto be'Jet'(line 76). - At lines 78–83 in
trace 6,colorbaris defined withtitle,orientation,x, andy.colorbaris set with a horizontal orientation (line 80) to avoid overlaying the legend.colorbar.xsets thexposition of the color bar, with a number between or equal to -2 and 3.
The default value is 1.02.colorbar.ysets the y position of the color bar, with a number between or equal to -2 and 3. The default value is 0.5. Intrace 6,colorbar.xis set to 0.48 (line 81), andcolorbar.yis set to -0.2 (line 82). The location has been moved from the top (default for horizontal orientation) to the bottom, next totrace 6. It shows how the color dimension of scattered points matchescolorbar. - At line 94, the scatter chart with seven color dimensions is created.
colorbar: {
title: 'y = 0',
orientation: 'v',
}
Apparently, colorbar overlaps the legend. Instead of making colorbar horizontal, we can change the legend to be horizontal.
Here is the modified src/App.js.
- At lines 7–9,
legendis set to horizontal. - At lines 81–83, the orientation of
colorbaris removed. The default value is vertical ('v').
The above example shows that color dimension is vibrant and easy to use.
Configuration Options
When hovering on the upper right corner of a chart, modebar shows up with a list of buttons. From left to right, it is Download, Zoom, Pan, Box Select, Lasso Select, Zoom in, Zoom out, Autoscale, Reset axes, and Plotly Logo.
Download: It downloads the chart via the browser. By default, it downloads a PNG file of dimension700x450. Here is the example to configure it to download an SVG file named'custom_image', and of the dimension800x600.
const configObj = {
toImageButtonOptions: {
format: 'svg', // one of png, svg, jpeg, webp
filename: 'custom_image',
width: 800,
height: 600,
scale: 1, // multiply title/legend/axis/canvas sizes by this factor
},
};
Setting scrollZoom to true allows users to zoom in and out using the scroll wheel on the mouse.
const configObj = {
scrollZoom: true,
};
Box Select: It allows selecting part of the chart with a box.Lasso Select: It allows selecting part of the chart with a free boundary.Zoom in: It makes the image bigger and closer.Zoom out: It makes the image smaller and farther.Autoscale: It looks at all the points (data) in the plot and changes the layout to show all of them.Reset axes: It goes back to the layout details specified for the chart, even if that leaves some points out.Plotly Logo: The tooltip shows the Plotly version, and clicking it goes to https://plotly.com/.
<Plot layout={layoutObj} data={dataArray} config={configObj} />
- Turn off the width and height responsiveness:
const configObj = {
responsive: false,
};
const configObj = {
staticPlot: true,
};
const configObj = {
displayModeBar: true,
};
const configObj = {
displaylogo: false,
};
const configObj = {
modeBarButtonsToRemove: ['pan', 'lasso'], // Pan and Lasso are removed
};
const configObj = {
modeBarButtonsToAdd: [
'drawline',
'drawopenpath',
'drawclosedpath',
'drawcircle',
'drawrect',
'eraseshape',
],
};
Event Handler Props
In the previous section, we introduced Box Select and Lasso Select, These select parts of the chart. What is the use case for that?
The chart that listens to the select event can react to the user selection.
Here is the modified src/App.js:
- At line 10, it makes
Box selectas the default action ofmodebar. - At lines 98–101, it creates a config object, which makes the
modebaralways visible and hides the Plotly Logo on themodebar. - At lines 103–105, a select handler is created to log the
selectedinformation. - At line 109, the chart is created with props of
layout,data,config, andonSelected.
On the Inspect console, selected information is displayed, which can be used to build applications.
Here is the props list for event handlers: onAfterExport, onAfterPlot, onAnimated, onAnimatingFrame, onAnimationInterrupted, onAutoSize, onBeforeExport, onBeforeHover, onButtonClicked, onClick, onClickAnnotation, onDeselect, onDoubleClick, onError, onFramework, onHover, onInitialized, onLegendClick, onLegendDoubleClick, onPurge, onRelayout, onRelayouting, onRestyle, onRedraw, onSelected, onSelecting, onSliderChange, onSliderEnd, onSliderStart, onSunburstClick, onTransitioning, onTransitionInterrupted, onUnhover, onUpdate, and onWebGlContextLost.
Conclusion
棒グラフと散布図に対してplotly.jsがどのように機能するかを示しました。完全なチャート機能に加えて、そのカラーディメンションは鮮やかで使いやすいです。ボタンmodebarが多すぎて強力です。ただし、アクセシビリティに欠けています。
Highchartsと比較して、Plotly の統計および科学チャートは AI/データ サイエンス コミュニティで広く採用されています。次の記事で例を示します。
読んでくれてありがとう。
Want to Connect?
If you are interested, check out my directory of web development articles.
![とにかく、リンクリストとは何ですか?[パート1]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)



































