Sparklines in ggplot2

后端 未结 1 610
北海茫月
北海茫月 2021-01-31 04:46

Tufte Sparklines (as illustrated in his Beautiful Evidence) have been replicated in base graphics as part of YaleToolkit and further perfected as a res

相关标签:
1条回答
  • 2021-01-31 05:32

    Here is one approach to getting single colored points, as well as the three sets of labels and shaded quartile ranges:

    # Calculate the min and max values, which.min returns the first (like your example):
    mins <- group_by(d, Crime.Type) %>% slice(which.min(Crime.Rate))
    maxs <- group_by(d, Crime.Type) %>% slice(which.max(Crime.Rate))
    ends <- group_by(d, Crime.Type) %>% filter(Year == max(Year))
    quarts <- d %>%
      group_by(Crime.Type) %>%
      summarize(quart1 = quantile(Crime.Rate, 0.25),
                quart2 = quantile(Crime.Rate, 0.75)) %>%
      right_join(d)
    
    ggplot(d, aes(x=Year, y=Crime.Rate)) + 
      facet_grid(Crime.Type ~ ., scales = "free_y") + 
      geom_ribbon(data = quarts, aes(ymin = quart1, ymax = quart2), fill = 'grey90') +
      geom_line(size=0.3) +
      geom_point(data = mins, col = 'blue') +
      geom_text(data = mins, aes(label = Crime.Rate), vjust = -1) +
      geom_point(data = maxs, col = 'red') +
      geom_text(data = maxs, aes(label = Crime.Rate), vjust = 2) +
      geom_text(data = ends, aes(label = Crime.Rate), hjust = 0) +
      geom_text(data = ends, aes(label = Crime.Type), hjust = 0, nudge_x = 5) +
      expand_limits(x = max(d$Year) + (0.25 * (max(d$Year) - min(d$Year)))) +
      scale_x_continuous(breaks = seq(1960, 2010, 10)) +
      scale_y_continuous(expand = c(0.1, 0)) +
      theme_tufte(base_size = 15) +
      theme(axis.title=element_blank(),
            axis.text.y = element_blank(), 
            axis.ticks = element_blank(),
            strip.text = element_blank())
    

    I'm assuming you don't want a legend here. You can almost certainly make things more concise by merging some data.frames, but multiple geom calls seem to be easiest here.

    0 讨论(0)
提交回复
热议问题