Reputation: 680
I have a binary matrix, which the row names are usernames and col names are dates. How can I plot the data as explained in the example.
Example:
2011-1-6 2011-1-9 2011-1-15 2011-2-19 Labels
A 1 0 0 1 1
B 0 1 1 1 2
C 1 1 0 0 3
In this case, the desired graph would be like the following:
Upvotes: 0
Views: 825
Reputation: 16988
There are a few ways but I want to encourage using tidy data and ggplot2
. So assuming your matrix is named mat
:
library(tidyr)
library(dplyr)
library(ggplot2)
# or simply just use: library(tidyverse)
mat %>%
as.data.frame() %>%
mutate(id=rownames(.),
Labels = as.factor(Labels)) %>%
pivot_longer(cols=starts_with("2011")) %>%
filter(value==1) %>%
ggplot(aes(x=name, y=id, color=Labels)) +
geom_point() +
theme(axis.text.x = element_text(angle = 90))
returns a plot similar to your desired output.
So what did we do?
ggplot
to process the data.filter
) all value == 0
rows, since only the value == 1
rows should be plottet.ggplot
to plot the data as scatter plot (geom_points
) with colors by Labels and rotated labels for the x-axis.Data
structure(c(1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 2, 3),
.Dim = c(3L, 5L),
.Dimnames = list(c("A", "B", "C"),
c("2011-1-6", "2011-1-9", "2011-1-15", "2011-2-19", "Labels")))
Upvotes: 2