ggplot2中的Sparklines

22
Tufte Sparklines(如其所述的在Beautiful Evidence中)已经在YaleToolkit中作为基础图形被复制,并通过this question得到了进一步的完善。Sparklines也已经作为我的小型副项目Tufte in R的一部分在lattice中完成(不打自拍)。我现在的目标是在ggplot2中复制Tufte sparklines。有一些脚本floating around on Gist,也作为this question on SO的回复,但它们都没有为制作可复制的sparkline集合提供一个坚实的基础。
现在,我希望这些多个小图表看起来像这样(它是基于图形的基础上完成的,代码在这里) - 点表示最大/最小值,右端的数字表示特定时间序列中的最终值,灰色带显示大致的分位数范围。

enter image description here

我离你不远,但是我卡在了有关最小/最大值和标签的任务上:

library(ggplot2)
library(ggthemes)
library(dplyr)
library(reshape)
library(RCurl)
dd <- read.csv(text =
  getURL("https://gist.githubusercontent.com/GeekOnAcid/da022affd36310c96cd4/raw/9c2ac2b033979fcf14a8d9b2e3e390a4bcc6f0e3/us_nr_of_crimes_1960_2014.csv"))
d <- melt(dd, id="Year")
names(d) <- c("Year","Crime.Type","Crime.Rate")
dd <- group_by(d, Crime.Type) %>% 
  mutate(color = (min(Crime.Rate) == Crime.Rate | max(Crime.Rate) == Crime.Rate))
ggplot(dd, aes(x=Year, y=Crime.Rate)) + 
  facet_grid(Crime.Type ~ ., scales = "free_y") + 
  geom_line(size=0.3) + geom_point(aes(color = color)) + 
  scale_color_manual(values = c(NA, "red"), guide=F) +
  theme_tufte(base_size = 15) + 
  theme(axis.title=element_blank(), 
        axis.text.y = element_blank(), axis.ticks = element_blank()) +
  theme(strip.text.y = element_text(angle = 0, vjust=0.2, hjust=0)) 

enter image description here

1个回答

25

以下是一种获取单颜色点及三组标签和阴影四分位范围的方法:

# 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())

假设您不需要图例。合并一些数据框几乎肯定可以使事情更简洁,但在这里使用多个geom调用似乎是最容易的。

enter image description here


2
...标签可以使用两个geom_text层来表示,需要适当设置vjust参数。 - joran
刚刚注意到我交换了颜色... -.- - Axeman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接