【发布时间】:2019-03-22 16:44:48
【问题描述】:
在 Facebook 研究中,我发现了这些漂亮的条形图,这些条形图由线条连接以指示排名变化:
https://research.fb.com/do-jobs-run-in-families/
我想使用 ggplot2 创建它们。条形图部分很简单:
library(ggplot2)
library(ggpubr)
state1 <- data.frame(state=c(rep("ALABAMA",3), rep("CALIFORNIA",3)),
value=c(61,94,27,10,30,77),
type=rep(c("state","local","fed"),2),
cumSum=c(rep(182,3), rep(117,3)))
state2 <- data.frame(state=c(rep("ALABAMA",3), rep("CALIFORNIA",3)),
value=c(10,30,7,61,94,27),
type=rep(c("state","local","fed"),2),
cumSum=c(rep(117,3), rep(182,3)))
fill <- c("#40b8d0", "#b2d183", "#F9756D")
p1 <- ggplot(data = state1) +
geom_bar(aes(x = reorder(state, value), y = value, fill = type), stat="identity") +
theme_bw() +
scale_fill_manual(values=fill) +
labs(x="", y="Total budget in 1M$") +
theme(legend.position="none",
legend.direction="horizontal",
legend.title = element_blank(),
axis.line = element_line(size=1, colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(), panel.background = element_blank()) +
coord_flip()
p2 <- ggplot(data = state2) +
geom_bar(aes(x = reorder(state, value), y = value, fill = type), stat="identity") +
theme_bw() +
scale_fill_manual(values=fill) + labs(x="", y="Total budget in 1M$") +
theme(legend.position="none",
legend.direction="horizontal",
legend.title = element_blank(),
axis.line = element_line(size=1, colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank()) +
scale_x_discrete(position = "top") +
scale_y_reverse() +
coord_flip()
p3 <- ggarrange(p1, p2, common.legend = TRUE, legend = "bottom")
但我无法想出解决线路部分的方法。添加行时,例如到左边
p3 + geom_segment(aes(x = rep(1:2, each=3), xend = rep(1:10, each=3),
y = cumSum[order(cumSum)], yend=cumSum[order(cumSum)]+10), size = 1.2)
基本上,我想将左侧的“加利福尼亚”栏与右侧的加利福尼亚栏连接起来。
我认为,要做到这一点,我必须以某种方式访问图表的上级。我查看了视口,并能够用由 geom_segment 制成的图表覆盖两个条形图,但后来我无法找出线条的正确布局:
subplot <- ggplot(data = state1) +
geom_segment(aes(x = rep(1:2, each=3), xend = rep(1:2, each=3),
y = cumSum[order(cumSum)], yend =cumSum[order(cumSum)]+10),
size = 1.2)
vp <- viewport(width = 1, height = 1, x = 1, y = unit(0.7, "lines"),
just ="right", "bottom"))
print(p3)
print(subplot, vp = vp)
非常感谢帮助或指点。
【问题讨论】:
-
alluvial可能是绘制线条的有用软件包(剩下的挑战是弄清楚如何在冲积地块上绘制条形图) -
很酷的问题!还可以考虑上传您的情节以吸引更多关注。
-
如果您可以计算条形图的相对 x/y 中心位置,您可以使用类似于
grid.lines(x = unit(c(.475, .525), "npc"), y = unit(c(.7, .4), "npc"))的东西,但这似乎非常骇人...... -
您能否详细说明您希望这些行如何连接?
cumSum未在您的代码中定义。
标签: r ggplot2 bar-chart data-visualization r-grid