ggplot2上的时间序列聚类可视化-不同的聚类颜色

时间:2020-09-07 03:45:18

标签: r ggplot2

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

Figure 1 Figure 2

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

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))

1 个答案:

答案 0 :(得分:0)

问题似乎是您在告诉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"))

enter image description here