Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2::geom_segment. How to set multiple sizes, say c(10,12)?

Tags:

r

ggplot2

I'm plotting with ggplot a data frame of different actions (A,B) not mutually exclusive and have multiple Ids. The activities often overlap within an Id, which might cause that some are not visible.

The data

df <- data.frame(id = c("id1", "id1", "id2", "id2"), x1 = c(10, 9, 12, 12 ), x2 = c(16, 17, 15, 19), type = c("A", "B", "A", "B"))

The codes

library("ggplot2")

This works:

ggplot2::ggplot() +
  geom_segment(data = df, aes(colour = type, x = x1, xend = x2, y = id, yend = id), size = 10)

Result: overlapping B and A. How to specify different geom_segment size?

Does not work:

ggplot2::ggplot() +
  geom_segment(data = df, aes(colour = type, x = x1, xend = x2, y = id, yend = id), size = c(10,12,10,12))

Error: Aesthetics must be either length 1 or the same as the data (2): size

like image 337
Edgar Santos Avatar asked Oct 19 '25 01:10

Edgar Santos


2 Answers

It looks like your sizes map to activity types. In that case you can just put size=type in the aesthetic mapping like any other part of your graph, and then specify how the different sizes will work using scale_size_discrete:

# Put all data and aesthetics that apply to the whole plot in the original
#   ggplot() call
ggplot2::ggplot(data = df, aes(colour = type, x = x1, xend = x2, y = id, yend = id, size=type)) +
    geom_segment() +
    # A is drawn first so make it bigger
    scale_size_discrete(range=c(12, 8))

Result:

Plot with sizes mapped to activity types

like image 101
Marius Avatar answered Oct 22 '25 05:10

Marius


ggplot2::ggplot() +
  geom_segment(data = df[df$type=="A", ], aes(colour = type, x = x1, xend = x2, y = id, yend = id), size = 12)+
  geom_segment(data = df[df$type=="B", ], aes(colour = type, x = x1, xend = x2, y = id, yend = id), size = 6)

enter image description here

like image 38
shiny Avatar answered Oct 22 '25 03:10

shiny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!