我有一个带有4个列的数据框。日期,渠道,公司A度量(stat105)和公司B度量(stat201)。
df <- data.frame(stringsAsFactors=FALSE,
station = c("K P1", "K P1", "K P1", "K P1", "K P1", "K P1", "K P1",
"P1 +", "P1 +", "P1 +", "P1 +", "P1 +", "P1 +", "P1 +",
"K P2", "K P2", "K P2", "K P2", "K P2", "K P2", "K P2", "mP3", "mP3",
"mP3", "mP3", "mP3", "mP3", "mP3", "P13", "P13", "P13", "P13",
"P13", "P13", "P13"),
date = c("2018-10-01", "2018-10-02", "2018-10-03", "2018-10-04",
"2018-10-05", "2018-10-06", "2018-10-07", "2018-10-01",
"2018-10-02", "2018-10-03", "2018-10-04", "2018-10-05", "2018-10-06",
"2018-10-07", "2018-10-01", "2018-10-02", "2018-10-03",
"2018-10-04", "2018-10-05", "2018-10-06", "2018-10-07", "2018-10-01",
"2018-10-02", "2018-10-03", "2018-10-04", "2018-10-05",
"2018-10-06", "2018-10-07", "2018-10-01", "2018-10-02", "2018-10-03",
"2018-10-04", "2018-10-05", "2018-10-06", "2018-10-07"),
stat105 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 270L, 251L, 317L, 342L,
378L, 0L, 0L, 291L, 460L, 515L, 299L, 462L, 0L, 0L, 0L, 42L,
119L, 107L, 21L, 0L, 0L, 0L, 63L, 40L, 0L, 63L),
stat201 = c(1221L, 1231L, 1176L, 1098L, 1092L, 952L, 826L, 310L, 310L,
289L, 268L, 252L, 312L, 316L, 245L, 254L, 261L, 246L, 227L,
143L, 181L, 114L, 104L, 134L, 158L, 183L, 153L, 152L, 108L, 126L,
113L, 127L, 137L, 64L, 87L)
)
我想在折线图上可视化/比较公司A和公司B每天每个通道的测量结果。我使用tidyr :: spread使数据整洁,但我的代码段仅适用于一个变量(stat105)。如何在折线图上比较/可视化stat105和stat201
library(tidyverse)
library(plotly)
# create tibble
df <- as.tibble(df) %>%
mutate(date = parse_date(date))
# tidy data
df_2 <- df %>%
select(-stat201) %>%
spread(station,stat105) %>%
janitor::clean_names()
#create plot with plotly
p <- plot_ly(df_2, x = ~date, y = ~k_p1, name = 'k_p1', type = 'scatter', mode = 'lines',
line = list(color = 'rgb(205, 12, 24)', width = 4)) %>%
add_trace(y = ~k_p2, name = 'k_p2', line = list(color = 'rgb(22, 96, 167)', width = 4)) %>%
add_trace(y = ~m_p3, name = 'm_p3', line = list(color = 'rgb(205, 12, 24)', width = 4, dash = 'dash')) %>%
add_trace(y = ~p1, name = 'p1', line = list(color = 'rgb(22, 96, 167)', width = 4, dash = 'dash')) %>%
add_trace(y = ~p13, name = 'p13', line = list(color = 'rgb(205, 12, 24)', width = 4, dash = 'dot')) %>%
layout(title = "Change in something",
xaxis = list(title = "Week"),
yaxis = list (title = "something"))
答案 0 :(得分:1)
这是一种使用ggplot
的方法,然后使用ggplotly将其发送到plotly:
df_3 <- df %>%
gather(stat_type, value, stat105:stat201)
my_blue <- "#1660a7"
my_red <- "#cd0c18"
a <- ggplot(df_3, aes(date, value, color = station, lty = station)) +
geom_line() +
facet_wrap(~stat_type, ncol = 1) +
scale_color_manual(values = c(my_red, my_blue, my_red, my_blue, my_red)) +
scale_linetype_manual(values = c("solid", "solid", "dashed", "dashed", "dotted")) +
labs(title = "Change in something", x = "Week", y = "something")
ggplotly(a)