这是一个带有 ggplot2 的堆积饼图。数据中的百分比在每一年内都不会达到 100%,因此为了本示例的目的,我将它们缩放为 100%(如果您的真实数据没有耗尽,您可以改为添加“其他”类别所有选项)。我还将列的名称c 更改为cc,因为c 是一个R 函数。
library(tidyverse)
# Convert cc to numeric
df$cc = as.numeric(as.character(df$cc))
# Data for plot
pdat = df %>%
group_by(year) %>%
mutate(cc = cc/sum(cc)) %>%
arrange(browser) %>%
# Get cumulative value of cc
mutate(cc_cum = cumsum(cc) - 0.5*cc) %>%
ungroup
ggplot(pdat, aes(x=cc_cum, y=year, fill=browser)) +
geom_tile(aes(width=cc), colour="white", size=0.4) +
geom_text(aes(label=sprintf("%1.1f", 100*cc)), size=3, colour="white") +
geom_text(data=pdat %>% filter(year==median(year)), size=3.5,
aes(label=browser, colour=browser), position=position_nudge(y=0.5)) +
scale_y_continuous(breaks=min(pdat$year):max(pdat$year)) +
coord_polar() +
theme_void() +
theme(axis.text.y=element_text(angle=0, colour="grey40", size=9),
axis.ticks.y=element_line(),
axis.ticks.length=unit(0.1,"cm")) +
guides(fill=FALSE, colour=FALSE) +
scale_fill_manual(values=hcl(seq(15,375,length=6)[1:5],100,70)) +
scale_colour_manual(values=hcl(seq(15,375,length=6)[1:5],100,50))
您也可以使用堆积条形图,这可能更清晰:
ggplot(pdat, aes(x=cc_cum, y=year, fill=browser)) +
geom_tile(aes(width=cc), colour="white") +
geom_text(aes(label=sprintf("%1.1f", 100*cc)), size=3, colour="white") +
geom_text(data=pdat %>% filter(year == min(year)), size=3.2,
aes(label=browser, colour=browser), position=position_nudge(y=-0.6)) +
scale_y_continuous(breaks=min(df$year):max(df$year)) +
scale_x_continuous(expand=c(0,0)) +
theme_void() +
theme(axis.text.y=element_text(angle=0, colour="grey40", size=9),
axis.ticks.y=element_line(),
axis.ticks.length=unit(0.1,"cm")) +
guides(fill=FALSE, colour=FALSE) +
scale_fill_manual(values=hcl(seq(15,375,length=6)[1:5],100,70)) +
scale_colour_manual(values=hcl(seq(15,375,length=6)[1:5],100,50))
线图可能是最清晰的:
library(scales)
ggplot(pdat, aes(year, cc, colour=browser)) +
geom_line() +
geom_label(aes(label=sprintf("%1.1f", cc*100)), size=3,
label.size=0, label.padding=unit(1,"pt"), , colour="white") +
geom_text(aes(label=sprintf("%1.1f", cc*100)), size=3) +
geom_text(data=pdat %>% filter(year==max(year)),
aes(label=browser), hjust=0, nudge_x=0.08, size=3) +
theme_classic() +
expand_limits(x=max(pdat$year) + 0.3, y=0) +
guides(colour=FALSE) +
scale_x_continuous(breaks=min(pdat$year):max(pdat$year)) +
scale_y_continuous(labels=percent)