RでPlotlyを使用する

R
Plotly
Published

August 22, 2024

#install.packages("plotly")
library(plotly)
Loading required package: ggplot2

Attaching package: 'plotly'
The following object is masked from 'package:ggplot2':

    last_plot
The following object is masked from 'package:stats':

    filter
The following object is masked from 'package:graphics':

    layout
x <- 1:10
y <- 1:10
y2 <- 5:14
d <- data.frame(x, y, y2)
d
    x  y y2
1   1  1  5
2   2  2  6
3   3  3  7
4   4  4  8
5   5  5  9
6   6  6 10
7   7  7 11
8   8  8 12
9   9  9 13
10 10 10 14
plot_ly(d, x = ~x, y = ~y, type = "scatter", mode = "markers")

typemodeを指定しないと、プロット自体はできるものの、警告が表示されます。

plot_ly(d, x = ~x, y = ~y)
No trace type specified:
  Based on info supplied, a 'scatter' trace seems appropriate.
  Read more about this trace type -> https://plotly.com/r/reference/#scatter
No scatter mode specifed:
  Setting the mode to markers
  Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode

type = scatterでOKです。 modelines, markers, lines+markers, lines+markers+text, noneのような感じで指定します。

R Figure Reference: Single Page - scatter R Figure Reference: Single Page - scatter-mode

plot_ly(d, x = ~x, y = ~y, type = "scatter", mode = "lines")
plot_ly(d, x = ~x, y = ~y, type = "scatter", mode = "lines+markers")

系列の追加

系列の追加には、add_trace関数を使用します。 適当なオブジェクトにプロットを保存して追加していきます。 完成したらオブジェクト名を書けばプロットが描画されます。

p <- plot_ly(d, x = ~x, y = ~y, type = "scatter", mode = "markers")
p <- add_trace(p, data = d, x = ~x, y = ~y2, type = "scatter", mode = "lines")
p

最初にベースプロットを描き、そのあとに追加していくこともできます。

p <- plot_ly()
p <- add_trace(p, data = d, x = ~x, y = ~y, type = "scatter", mode = "markers")
p <- add_trace(p, data = d, x = ~x, y = ~y2, type = "scatter", mode = "lines")
p

add_tracetypeを問いませんが、typeが決まっている場合は、特定のadd_markersadd_linesのように関数の時点で指定することもできます。

p <- plot_ly()
p <- add_markers(p, data = d, x = ~x, y = ~y)
p <- add_lines(p, data = d, x = ~x, y = ~y2)
p

お好みで使い分けると良いと思います。

参考になるサイト

Plotly R Open Source Graphing Library

https://plotly-r.com

Back to top