brancz
brancz

Reputation: 451

dotplot with ggplot2 grouping the y values

I have a data-set similar to this

products <- c('Product1', 'Product2', 'Product3', 'Product3', 'Product1', 'Product1')
timestamp <- c(1,2,3,4,5,6)
categories <- c('Category1', 'Category2', 'Category1', 'Category1', 'Category1', 'Category1')
data <- data.frame(timestamp, products, categories)

Now I would like to draw a dotplot with ggplot2 like so

ggplot(data, aes(timestamp, products, colour=categories, group=categories)) + geom_point()

Which produces the following chart

enter image description here

Which is almost what I what, however, I would like to group the products in categories as they are in this chart:

dotchart(data$timestamp, labels=data$products, groups=data$categories, color=data$color)

enter image description here

It is important to plot occurrences of a product for the same y-value (like in the first plot), instead of repeating it for every record as it is done in the second plot.

Upvotes: 3

Views: 2827

Answers (1)

mathematical.coffee
mathematical.coffee

Reputation: 56935

You could try just making a new y column like so:

type <- paste(data$categories, data$products)
# convert to a factor and sort the levels reverse-alphabetical (so it is in order top-down on the plot)
type <- factor(type, levels=sort(unique(type), dec=T))
data$type <- type
ggplot(data, aes(timestamp, type, colour=categories)) + geom_point()

enter image description here

though the y axis text is not laid out like in the dotchart.

Or you could use facet_wrap for something similar but a bit different (don't need the type thing then):

ggplot(data, aes(timestamp, products, colour=categories)) + geom_point() + facet_wrap( ~ categories,ncol=1)

enter image description here

This one provides more separation of your categories and has the advantage (or perhaps disadvantage, depending on your opinion) of showing "empty" level combinations (e.g. category 2 product 1). If you don't like that add scales="free_y":

ggplot(data, aes(timestamp, products, colour=categories)) + geom_point() + facet_wrap( ~ categories, ncol=1, scales="free_y")

enter image description here

Upvotes: 5

Related Questions