我想在我的数据中显示两个维度,(1)不同方面的报告实体和(2)与x轴上的数据点相关联的国家.问题是国家维度包括一个"总数",它比所有单个值都高很多,所以我需要一个自己的轴限制.
我的解决方案是尝试另一个刻面维度,但我无法让它工作并且在同一时间看起来很好.考虑以下虚拟数据:
id <- c(1,1,1,1,1,1,2,2,2,2,2,2)
country <- c("US","US","UK","World","World","World","US","US","UK","World","World","World")
value <- c(150,40,100,1000,1100,1500,5,10,20,150,200,120)
# + some other dimensions
mydat <- data.frame(id,country,value)
id country value
1 1 US 150
2 1 US 40
3 1 UK 100
4 1 World 1000
5 1 World 1100
6 1 World 1500
7 2 US 5
8 2 US 10
9 2 UK 20
10 2 World 150
11 2 World 200
12 2 World 120
Run Code Online (Sandbox Code Playgroud)
如果我使用构面网格显示世界总数,则也会强制其他国家/地区的轴限制:
mydat$breakdown <- mydat$country == "World"
ggplot(mydat) + aes(x=country,y=value) + geom_point() +
facet_grid(id ~ breakdown,scales = "free",space = "free_x") +
theme(strip.text.x = element_blank() , strip.background = element_blank(),
plot.margin = unit( c(0,0,0,0) , units = "lines" ) )
Run Code Online (Sandbox Code Playgroud)
(图的最后一部分只是删除附加条带).
如果我使用facet wrap,它确实为每个绘图提供了不同的轴限制,但是我无法传递space = "free_x"参数,这意味着total的单个列将占用与整个国家概述相同的空间,这对于数据看起来很难看与许多国家集合:
ggplot(mydat) + aes(x=country,y=value) + geom_point() +
facet_wrap(id ~ breakdown,scales = "free")
Run Code Online (Sandbox Code Playgroud)
这里有几个线程提出类似的问题,但没有一个答案帮助我实现了这个目标.
也许尝试gridExtra::grid.arrange或cowplot::plot_grid:
lst <- split(mydat, list(mydat$breakdown, mydat$id))
plots <- lapply(seq(lst), function(x) {ggplot(lst[[x]]) +
aes(x=country,y=value) +
geom_point() +
ggtitle(names(lst)[x]) + labs(x=NULL, y=NULL)
})
do.call(gridExtra::grid.arrange,
c(plots, list(ncol=2, widths=c(2/3, 1/3)),
left="Value", bottom="country"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
930 次 |
| 最近记录: |