使用这个可重现的例子tibble
# install and attach packages
if (!require("pacman")) install.packages("pacman")
pacman::p_load(tidyverse, dplyr, ggplot2)
# Create example dataset (tib1)
tib1 = tibble(location = c("loc1", rep(c("loc1", "loc2"), 8), rep("loc2",2)),
drill = sort(c(1, rep(1:4, 4),4, 4)),
thickness = c(20, 34, 99, 67, 29, 22, 53, 93, 64, 98, 76, 42, 49, 23, 11, 74,
19, 50, 40),
soiltype = c("gravel", rep( c("sand", "loam", "clay"),5 ), "sand", "gravel", "clay")) %>%
arrange(location, drill)
tib1 <- tib1 %>% group_by(location, drill) %>%
mutate(order = row_number(),
bottom_of_layer = cumsum(thickness),
top_of_layer = bottom_of_layer-thickness) %>%
ungroup %>%
select(location, drill, bottom_of_layer, top_of_layer, thickness, soiltype, order)
tib1
我想绘制土壤的横截面。我尝试使用geom_bar
或geom_col
从ggplot2
. 在示例数据中,给出了一个顺序 (1:3)。我希望按照“订单列”中指定的顺序堆叠条形图。所以这会暗示酒吧在哪里:
- location == "loc2"和Drill == 4应该按顺序着色(从上到下):
橙色(壤土)-黄色(沙子)-灰色(砾石)-海绿色(粘土)
和
- location == "loc1"和Drill == 1应该按顺序着色(从上到下):
灰色(砾石)-黄色(沙子)-海绿色(粘土)
而其他堆叠的条保持相同的顺序和颜色。
换句话说:我需要堆积条中的颜色随着“顺序”列中指示的顺序而变化。
colpalette = c("darkseagreen3", "darkgrey", "#FF9966", "palegoldenrod")
ggplot(tib1,
aes(x = drill))+
geom_bar(aes(fill = soiltype, y = -thickness),
stat = "identity")+
scale_fill_manual(values = colpalette)+
facet_wrap(vars(location), scale = "free_x")+
xlab("drill")+
ylab("depth (cm)")+
ggtitle("how to plot the bars in the 'preferred order'? ",
subtitle = "the order of loc2 and drill == 4 should be: loam-sand-gravel-clay")+
theme_minimal()
可比较但略有不同的问题是:
我想知道我所要求的东西在 ggplot 中是否可能是:
当多个条形图放置在同一位置时,条形图会自动堆叠。填充顺序旨在匹配图例。
所以我可能不得不寻找替代选择......除非有人有黑客?任何帮助、答案、替代绘图选项、链接表示赞赏:) 如果可能的话,我更喜欢 ggplot2。