Tart
Tart

Reputation: 305

Show only data labels for every N day and highlight a line for a specific variable in R ggplot

I'm trying to figure out two problems in R ggplot:

  1. Show only data labels for every N day/data point
  2. Highlight (make the line bigger and/or dotted) for a specific variable

My code is below:

gplot(data = sales, 
        aes(x = dates, y = volume, colour = Country, size = ifelse(Country=="US", 1, 0.5) group = Country)) + 
        geom_line() + 
        geom_point() +
        geom_text(data = sales, aes(label=volume), size=3, vjust = -0.5)

I can't find out a way how to space the data labels as currently they are being shown for each data point per every day and it's very hard to read the plot.
As for #2, unfortunately, the size with ifelse doesn't work as 'US' line is becoming super huge and I can't change that size not matter what I specify in the first parameter of ifelse.

Would appreciate any help!

Upvotes: 0

Views: 276

Answers (1)

stefan
stefan

Reputation: 125208

As no data was provided the solution is probably not perfect, but nonetheless shows you the general approach. Try this:

sales_plot <- sales %>% 
  # Create label
  # e.g. assuming dates are in Date-Format labels are "only" created for even days
  mutate(label = ifelse(lubridate::day(dates) %% 2 == 0, volume, ""))

ggplot(data = sales_plot, 
       # To adjust the size: Simply set labels. The actual size is set in scale_size_manual
      aes(x = dates, y = volume, colour = Country, size = ifelse(Country == "US", "US", "other"), group = Country)) + 
  geom_line() + 
  geom_point() +
  geom_text(aes(label = label), size = 3, vjust = -0.5) +
  # Set the size according the labels
  scale_size_manual(values = c(US = 2, other = .9))

Upvotes: 1

Related Questions