Letakkan beberapa diagram sebar pada setiap grafik subplot
Aug 21 2020
Saya memiliki dataframe, yang dapat dibuat dengan kode ini:
x = data.frame(metrics=c("type1", "type1", "type1","type1", "type1", "type1", "orders", "orders", "orders","orders", "orders", "orders", "mean","mean","mean","mean","mean","mean"), hr=c(6,7,8,6,7,8,6,7,8,6,7,8,6,7,8,6,7,8), actual=c(14,20,34,22,24,27,56,12,34,11,15,45,56,78,89,111,123,156), time=c("today", "yesterday", "today", "yesterday", "today", "yesterday"))
Saya ingin memvisualisasikan data ini menggunakan fungsi plot_ly. Saya ingin membuat tiga subplot untuk setiap jenis nilai di kolom "metrik". Selain itu, di setiap subplot harus ada dua diagram sebar untuk setiap jenis nilai di kolom "waktu" (hari ini, kemarin).
Saya melakukan semua, kecuali membuat dua diagram sebar untuk setiap jenis nilai di kolom "waktu" dengan warna berbeda:
plot <- function(df) {
subplotList <- list()
for(metric in unique(df$metrics)){ subplotList[[metric]] <- df[df$metrics == metric,] %>%
plot_ly(
x = ~ hr,
y = ~ actual,
name = metric,
hoverinfo = "text",
hovertemplate = paste(
"<b>%{text}</b><br>",
"%{xaxis.title.text}: %{x:+.1f}<br>",
"%{yaxis.title.text}: %{y:+.1f}<br>",
"<extra></extra>"
),
type = "scatter",
mode = "markers",
marker = list(
size = 18,
color = "white",
line = list(color = "black",
width = 1.5)
),
width = 680,
height = 420
)
}
subplot(subplotList, nrows = length(subplotList), margin = 0.1)
Saya mendapatkan grafik ini:

Bagaimana cara membuat kedua scatterplot ini pada setiap subplot memiliki warna yang berbeda?
Jawaban
ismirsehregal Aug 21 2020 at 11:33
Inilah yang menurut saya Anda cari:
library(plotly)
x = data.frame(metrics=c("type1", "type1", "type1","type1", "type1", "type1", "orders", "orders", "orders","orders", "orders", "orders", "mean","mean","mean","mean","mean","mean"), hr=c(6,7,8,6,7,8,6,7,8,6,7,8,6,7,8,6,7,8), actual=c(14,20,34,22,24,27,56,12,34,11,15,45,56,78,89,111,123,156), time=c("today", "yesterday", "today", "yesterday", "today", "yesterday"))
plot <- function(df) {
subplotList <- list()
for(metric in unique(df$metrics)){ subplotList[[metric]] <- df[df$metrics == metric,] %>%
plot_ly(
x = ~ hr,
y = ~ actual,
name = ~ paste(metrics, " - ", time),
colors = ~ time,
hoverinfo = "text",
hovertemplate = paste(
"<b>%{text}</b><br>",
"%{xaxis.title.text}: %{x:+.1f}<br>",
"%{yaxis.title.text}: %{y:+.1f}<br>",
"<extra></extra>"
),
type = "scatter",
mode = "markers",
marker = list(
size = 18,
color = "white",
line = list(width = 1.5)
),
width = 680,
height = 420
)
}
subplot(subplotList, nrows = length(subplotList), margin = 0.1)
}
plot(x)

Pertanyaan sebelumnya untuk pembaca mendatang.
Selalu Menjadi Ancaman: Mengapa Orang Berkulit Coklat dan Hitam Tidak Bisa Nyaman di Amerika Serikat