R语言 有没有办法在ggplot2中为条形图添加条纹?

ubof19bj  于 2023-05-11  发布在  其他
关注(0)|答案(1)|浏览(173)

我有六个网站,我想成为条形图,与网站名称的X轴和利率(数字)对我的Y轴。我的网站是网站1,网站1硬木,网站2,网站2硬木,网站3,网站3硬木。我希望硬木网站的酒吧是相同的颜色,其相应的网站,但有条纹。我可以创建条形图本身,但添加条纹一直更麻烦。

#Site set up
sites <- c("Mt. Grace", "Mt. Grace Hardwood", "White's Pond", "White's Pond Hardwood", "TriMountain", "TriMountain Hardwood")
nitr_rates <- c(-0.90855, -0.7161, -0.46017, -0.30943, -0.21913, 0.2995)
striped_sites <- c("Mt. Grace Hardwood", "White's Pond Hardwood", "TriMountain Hardwood") #Make these striped
Color <- c("#5BA300", "#5BA300", "#0073E6", "#0073E6", "#B51963", "#B51963")
Stripe <- ifelse(sites %in% striped_sites, "stripe", NA)
Nitri_data <- data.frame(sites, nitr_rates, Color, Stripe)
site_order <- c("Mt. Grace", "Mt. Grace Hardwood", "White's Pond", "White's Pond Hardwood", "TriMountain", "TriMountain Hardwood")

#Graph
ggplot(Nitri_data, aes(x = factor(sites, levels = site_order), y = nitr_rates, fill = Color)) +
  geom_bar(stat = "identity", color = "black", alpha = 0.7, aes(pattern = Stripe)) +
  scale_pattern_manual(values = c("stripe" = "stripe")) +
  scale_fill_manual(values = c("#5BA300", "#0073E6", "#B51963" ), guide = guide_legend(override.aes = list(fill = c("#5BA300", "#0073E6", "#B51963")))) +
  xlab("Site") +
  ylab("mg N/g dry wt. soil/28 days") +
  ggtitle("Net Nitrification") +
  theme_minimal() +
  theme(legend.position = "bottom")

这段代码创建了一个条形图与我的网站,但不包括条纹。

ee7vknir

ee7vknir1#

要获得一个模式,必须使用geom_col_pattern。此外,为了使这项工作,在您不需要模式的情况下,为Stripe分配一个非NA值,例如。我选择了"none"。最后,您可以使用scale_pattern_identity来应用这些模式。

library(ggplot2)
library(ggpattern)

Nitri_data$Stripe <- ifelse(Nitri_data$sites %in% striped_sites, "stripe", "none")

ggplot(Nitri_data, aes(x = factor(sites, levels = site_order), y = nitr_rates, fill = Color)) +
  geom_col_pattern(color = "black", alpha = 0.7, aes(pattern = Stripe)) +
  scale_pattern_identity() +
  scale_fill_manual(
    values = c("#5BA300", "#0073E6", "#B51963")
  ) +
  xlab("Site") +
  ylab("mg N/g dry wt. soil/28 days") +
  ggtitle("Net Nitrification") +
  theme_minimal() +
  theme(legend.position = "bottom")

相关问题