如何使用具有日期的ggplot在R中可视化交互式折线图
how to visualize interactive line chart in R using ggplot having date
我有以下数据集,我想通过库(plotly)在折线图中或任何使用 R 中的 ggplot 的东西中可视化它并添加 add_trace 函数
structure(list(Date = structure(c(18049, 18050, 18051, 18052), class = "Date"),
x = c(23L, 0L, 54L, 62L), y = c(45L, 72L, 10L, 21L), Total = c(68L,
72L, 156L, 83L)), class = "data.frame", row.names = c(NA,
-4L))
我想在 R 中使用 ggplot 可视化折线图中的数据、x、y 列。谢谢
您可以尝试这种 tidyverse
和 plotly
方法。您必须首先将数据重塑为 long ,然后才能绘制。这是代码。我使用了类似于发布的虚拟数据:
library(tidyverse)
library(plotly)
#Code
#Prepare data
df1 <- df %>%
#First format date
mutate(Date=as.Date(Date,'%d/%m/%Y')) %>%
#Reshape
pivot_longer(cols = -1)%>%
#Filter out total
filter(name!='Total')
#Plot
plot_ly(df1,
x = ~Date,
y = ~value,
name=~name,
type = 'scatter',
mode = 'lines')
输出:
使用了一些数据:
#Data
df <- structure(list(Date = c("02/06/2019", "03/06/2019", "04/06/2019",
"05/06/2019"), x = c(23L, 0L, 54L, 62L), y = c(45L, 72L, 102L,
21L), Total = c(68L, 72L, 156L, 83L)), class = "data.frame", row.names = c(NA,
-4L))
这样你就可以到达一个互动情节。如果您重塑数据,则可以避免使用大量 add_trace()
函数。让我知道这是否适合你。
这是第二种方法,无需重塑数据,直接使用 plotly
包。
plot_ly(df, x = ~Date) %>%
add_trace(y = ~x, name = "x", type = "scatter", mode = "lines") %>%
add_trace(y = ~y, name = "y", type = "scatter", mode = "lines")
或者只是简单地在 ggplot
中结合函数 ggplotly
.
g <- ggplot(df, aes(x = Date)) +
geom_line(aes(y = x, color = "a")) +
geom_line(aes(y = y, color = "b")) +
scale_color_manual(name = "Colors",
values = c("a" = "blue", "b" = "red"))
ggplotly(g)
我有以下数据集,我想通过库(plotly)在折线图中或任何使用 R 中的 ggplot 的东西中可视化它并添加 add_trace 函数
structure(list(Date = structure(c(18049, 18050, 18051, 18052), class = "Date"),
x = c(23L, 0L, 54L, 62L), y = c(45L, 72L, 10L, 21L), Total = c(68L,
72L, 156L, 83L)), class = "data.frame", row.names = c(NA,
-4L))
我想在 R 中使用 ggplot 可视化折线图中的数据、x、y 列。谢谢
您可以尝试这种 tidyverse
和 plotly
方法。您必须首先将数据重塑为 long ,然后才能绘制。这是代码。我使用了类似于发布的虚拟数据:
library(tidyverse)
library(plotly)
#Code
#Prepare data
df1 <- df %>%
#First format date
mutate(Date=as.Date(Date,'%d/%m/%Y')) %>%
#Reshape
pivot_longer(cols = -1)%>%
#Filter out total
filter(name!='Total')
#Plot
plot_ly(df1,
x = ~Date,
y = ~value,
name=~name,
type = 'scatter',
mode = 'lines')
输出:
使用了一些数据:
#Data
df <- structure(list(Date = c("02/06/2019", "03/06/2019", "04/06/2019",
"05/06/2019"), x = c(23L, 0L, 54L, 62L), y = c(45L, 72L, 102L,
21L), Total = c(68L, 72L, 156L, 83L)), class = "data.frame", row.names = c(NA,
-4L))
这样你就可以到达一个互动情节。如果您重塑数据,则可以避免使用大量 add_trace()
函数。让我知道这是否适合你。
这是第二种方法,无需重塑数据,直接使用 plotly
包。
plot_ly(df, x = ~Date) %>%
add_trace(y = ~x, name = "x", type = "scatter", mode = "lines") %>%
add_trace(y = ~y, name = "y", type = "scatter", mode = "lines")
或者只是简单地在 ggplot
中结合函数 ggplotly
.
g <- ggplot(df, aes(x = Date)) +
geom_line(aes(y = x, color = "a")) +
geom_line(aes(y = y, color = "b")) +
scale_color_manual(name = "Colors",
values = c("a" = "blue", "b" = "red"))
ggplotly(g)