kni*_*ick 3 r ggplot2 facet-wrap geom-bar
我有一个数据框:
df1 <- data.frame(place = c("a", "a", "b", "b", "c", "c", "d", "d", "e", "e", "f", "f", "g", "g",
"h", "h", "i", "i", "j", "j", "k", "k", "l", "l", "m", "m", "n",
"n", "o", "o", "p", "p", "q", "q"),
cost_other = c("cost_savings", "other_savings",
"cost_savings", "other_savings",
"cost_savings", "other_savings",
"cost_savings", "other_savings",
"cost_savings", "other_savings",
"cost_savings", "other_savings",
"cost_savings", "other_savings",
"cost_savings", "other_savings",
"cost_savings", "other_savings",
"cost_savings", "other_savings",
"cost_savings", "other_savings",
"cost_savings", "other_savings",
"cost_savings", "other_savings",
"cost_savings", "other_savings",
"cost_savings", "other_savings",
"cost_savings", "other_savings",
"cost_savings", "other_savings"),
values = c(1.8,0.55, 0.836, 1.06, 1.096, 1.83875908682016,
0.966, 1.34497094648805, 1.62275, 0.600277163210231, 0.873875,
0.875130680022367, 1.487, 0.283241350805961, 1.0776, 0.849116238360361,
1.221, 1.45510685371131, 0.961882352941176, 1.30607084680655,
1.027, 1.52026452067783, 0.807666666666667, 1.22377282341786,
0.788384615384615, 0.984172521942087, 0.975, 1.94002090880358,
1.00333333333333, 1.18402178405582, 0.8956, 1.16165422673896,
0.95975, 0.825533052928448))
Run Code Online (Sandbox Code Playgroud)
我想使用这些数据创建一个基于分面包裹的 geom_bar 图表,以便每个分面空间都以灰色显示所有条形图。然后,我需要特定网格的特定条形为任何颜色。
我尝试这样做,但得到了这样的结果:

我用它来得到我的结果:
ggplot(data=df,aes(x=place,
y=values))+
geom_bar(aes(fill=cost_other),
stat = "identity",
position = "dodge") +
facet_wrap(~place) +
theme_calc()+
theme(legend.position = "none",
axis.text.x=element_blank())
Run Code Online (Sandbox Code Playgroud)
我得到了特定的颜色条,但所有其他空间都是空的。我还想要所有变量的其他条形图,特别是灰色的。
使用tidyr::expand_grid(),创建一个place_facet具有唯一值 的列place,并将其与初始数据交叉。这将为您提供一个扩展的数据框,为每个方面复制一次原始数据。然后绘制两层条形图:一层使用所有值显示为灰色,另一层显示为颜色,仅显示place和place_facet匹配的值。
library(tidyr)
library(dplyr)
library(ggplot2)
library(ggthemes)
df1 %>%
tidyr::expand_grid(place_facet = unique(.$place)) %>%
mutate(values_facet = ifelse(place == place_facet, values, NA)) %>%
ggplot(aes(x = place)) +
geom_col(
aes(y = values, group = cost_other),
position = "dodge",
fill = "gray"
) +
geom_col(
aes(y = values_facet, fill = cost_other),
position = "dodge",
show.legend = FALSE
) +
facet_wrap(~place_facet) +
theme_calc() +
theme(axis.text.x = element_blank())
Run Code Online (Sandbox Code Playgroud)