Ehabid lopez
Ehabid lopez

Reputation: 33

How do you make groups for a variable in ggplot?

So I have the following code:

base_99 <- ggplot(df, aes(dates, y, colour = text$likes_count)) + geom_point() + 
  labs(y ='Número de palabras por tweet', x='Años', color = 'Número de likes por tweet')

which gives me the following scatterplot: enter image description here

I want to have groups of the color legend. For example: 0:30, 31-61, 62:91, 92:121 How can I do that in ggplot? Thank you

Upvotes: 1

Views: 121

Answers (1)

Olsgaard
Olsgaard

Reputation: 1582

I think the problem is your likes counts are stored as a character vector instead of a integer-vector.

I think it will work (or at least give you a useful legend, but perhaps different from what you considered) if you convert $text$likes_count to integers.

Without data, I can't test if it gives you the results you want, but try

base_99 <- ggplot(df, aes(dates, y, colour = as.integer(text$likes_count))) + geom_point() + 
  labs(y ='Número de palabras por tweet', x='Años', color = 'Número de likes por tweet')

You can also use cut to break the numbers into a series of ranges.

Again, I can't test, but try:

base_99 <- ggplot(
    df, aes(dates, y, colour = cut(as.integer(text$likes_count), 10))) + 
  geom_point() + 
  labs(y ='Número de palabras por tweet', x='Años', color = 'Número de likes por tweet')

Upvotes: 1

Related Questions