【问题标题】:How to make Financial Times faceted charts with ggplot2 in R如何在 R 中使用 ggplot2 制作《金融时报》多面图表
【发布时间】:2020-04-07 09:13:25
【问题描述】:

《金融时报》有一张漂亮的多面冠状病毒图表:查看每日死亡人数https://www.ft.com/coronavirus-latest 你知道如何使用 R 和 ggplot2 制作它吗?

Facet_wrap 函数在这种情况下没有用,它将每个国家行分隔为单个 minigraph。其他国家/地区以灰色不可见。

我应该准备 20 多个图表并使用 gridExtra::grid.arrange() 加入它们吗?

【问题讨论】:

  • 谢谢,看起来很有用,我试试看。
  • grid.arrange 可能是实现这一目标的好方法,尽管我怀疑你能否得到完全相同的图表。首先,您可以使用参数国家名称构建一个函数。 f(country) 将生成一个带有突出显示的国家和国家名称的图。然后你可以遍历所有国家并安排网格。需要一些更精确的数据你能找到吗?
  • gghighlight 真的是一个很棒的包。我可以让这个图表只在 ggplot 代码中添加一行 gghighlight()。

标签: r ggplot2


【解决方案1】:

我在想是否有办法在不复制data.frame的情况下绘制上面的图,所以我模拟了一些数据:

set.seed(111)
data = data.frame(group=rep(letters[1:6],each=60),
do.call(rbind,
replicate(6,
data.frame(x=1:60,y=cumsum(rnbinom(60,mu=20,size=0.1))),simplify=FALSE))
)

下面我遍历每个组并创建一个 data.frame,另一个名为“highlight”的列用于注释感兴趣的组:

library(purrr)
library(ggthemes)
library(ggplot2)
library(dplyr)

unique(data$group) %>% 
map_dfr(~cbind(data,facet=.x,highlight=data$group %in% .x)) %>% 
ggplot(aes(x=x,y=y,group=group))+
geom_line(aes(col=highlight)) + 
facet_wrap(~facet,ncol=3,scales="free") + 
theme_tufte() + scale_color_manual(values=c("#e5dfdf","#357376"))  +
theme(strip.text=element_text(size=12,colour="steelblue"))+
guides(colour = "none")

当然可以创建一个 ggplots 列表,但实际上你也在复制数据(ggplot 在下面创建一个 data.frame):

plotfun = function(data,highlight){
data %>% 
mutate(highlight = group == highlight) %>%
ggplot(aes(x=x,y=y,group=group))+
geom_line(aes(col=highlight)) + 
theme_tufte() + scale_color_manual(values=c("#e5dfdf","#357376"))  +
ggtitle(highlight)+ 
theme(plot.title = element_text(size=12,colour="steelblue"))+
guides(colour = "none")
}

grid.arrange(grobs=unique(data$group) %>% map(~plotfun(data,.x)),ncol=3)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    相关资源
    最近更新 更多