【问题标题】:Time series clustering visualization on ggplot2- different cluster colorsggplot2上的时间序列聚类可视化-不同的聚类颜色
【发布时间】:2020-12-25 11:46:08
【问题描述】:

我已使用动态时间扭曲将层次聚类应用于以下数据集。当我使用 ggplot2 绘制图表时,我希望不同的集群具有不同的颜色,而不是每个时间序列的不同颜色(当前显示在图 1:车辆集群中)。图 2 是我尝试实现此目的时得到的结果。它似乎正确地为集群着色,但在我不想要的中间填充。我怀疑这与 group_by 函数有关,并且当我尝试使用 mutate 函数时。

为了完整起见,我已经包含了原始数据集和程序。谢谢

library(ggplot2)
library(fpc)
library(readr)
library(plotly)
library(dplyr)
library(tidyr)
library(dtw)
library(gghighlight)

#Importing data
df <- read_csv("01_tracks.csv")

#Preparing data 
df1 <- filter(df,laneId == 2, width <= 6) #Filtering to only lane 3 and no trucks
#df1$id <- as.numeric(df1$id)
df1$xVelocity <- abs(df1$xVelocity)

#Creates a Data Frame of just the x-Velocity
df2 <- df1 %>% 
  group_by(id) %>%
  mutate(time = 1:n()) %>%
  dplyr::select(time, xVelocity) %>%
  pivot_wider(id_cols = time, values_from = xVelocity,
              names_from = id) %>%
  select(-time) %>%
  t()

 tdf <- df2[1:10,] #Only using first 10 vehicles to make computing time quick for convience in tests

xy.list <- setNames(split(tdf, seq(nrow(tdf))), rownames(tdf)) #Turn the data frame into a list
new.list <- lapply(xy.list, function(x) x[!is.na(x)]) #Take out all the NA values in the list

#Hierarchial Clustering
distance.matrix <- dist(new.list, method= "DTW") #Create a distance Matrix
hc <- hclust(distance.matrix, method= "average") #Performing hierarchical clustering

#Processing cluster groups
Number_of_clusters <- 3
clustered_data <- cutree(hc, k = Number_of_clusters)
clustered_data_tidy <- as.data.frame(as.table(clustered_data)) %>% glimpse()
colnames(clustered_data_tidy) <- c("id","cluster")
clustered_data_tidy$id <- as.character(clustered_data_tidy$id)
clustered_data_tidy$id <- as.numeric(clustered_data_tidy$id)

#Making a data frame with the cluster group
joined_clusters <- df1 %>% inner_join(clustered_data_tidy, by = "id") %>% glimpse()

  pl2 <- joined_clusters %>% #replace pl3 with joined_clusters
  group_by(id) %>%
  mutate(time = 1:n()) %>% #Creating time variable for the x-axis
  ggplot(aes(x = time, y = xVelocity)) + 
  geom_line(aes(color = cluster), show.legend = FALSE) +
  ggtitle(paste("Vehicle clusters"))
  print(gpl2 <- ggplotly(pl2))

【问题讨论】:

  • 您可以在问题中包含来自dput(joined_clusters) 的输出,而不是发布所有数据预处理代码+ 到完整数据集的链接?如果你问的是 ggplot2,前面的部分并不真正相关。

标签: r ggplot2


【解决方案1】:

问题似乎是您告诉 ggplot 您只需要三种不同颜色的三行,但您需要三种不同颜色的十行。

在您的 ggplot 调用中,您只传递了三个要映射到美学的变量:x 坐标、y 坐标和颜色。您没有告诉 ggplot 每种颜色中的 x 和 y 坐标应该分成不同的线,所以它只是将它们全部连接到每个颜色组中。

要解决此问题,您需要将车辆 ID 添加为 group 美学,以指定您仍希望单独绘制每条线的 x 和 y 坐标:

  joined_clusters %>%
    group_by(id) %>%
    mutate(time = 1:n()) %>%
    ggplot(aes(x = time, y = xVelocity)) + 
    geom_line(aes(color = factor(cluster), group = id), 
              size = 1, show.legend = FALSE) +
    ggtitle(paste("Vehicle clusters"))

【讨论】:

    猜你喜欢
    • 2015-04-02
    • 1970-01-01
    • 2015-07-22
    • 2021-10-04
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多