如何创建没有重叠条的 ggplot 条形图?

How can i create a ggplot bar chart without overlapping bars?

我的问题是,我需要创建条形图,而不需要条形相互重叠。我的数据的一个小例子是:

`structure(list(Variable = c("VPD", "Rg", "rH", "v2", "Ta", "p", 
"LWS", "rs", "cs"), day = c(NA, NA, NA, NA, 0.25, NA, NA, -0.2745, 
0.265), `p-value...3` = c(0.01125, 0.01308, 0.1965, 0.6166, 0.0004262, 
0.1596, 0.04293, 0.0002368, 0.000393), night = c(0.4824, NA, 
-0.366, NA, 0.7316, NA, NA, 0.2352, -0.2415), `p-value...5` = c(8.46e-07, 
0.4547, 0.0002104, 0.6055, 2.2e-16, 0.8818, 0.609, 0.01325, 0.0113
)), row.names = c(NA, -9L), class = c("tbl_df", "tbl", "data.frame"
))`

我用于绘图的代码是 (dput):

 ggplot(data=Mischbewuchs, aes(`Variable`))+
  geom_bar(aes(y=`day`),stat = "identity", fill="Orange")+
  geom_bar(aes(y=`night`),stat = "identity", fill="blue", width = 0.5, position = "dodge")+
  labs(y= "Spearman rank correlation coefficient", title = "a)")+
  geom_abline(intercept = 0, slope = 0, color="black")+
  theme_bw()

可以看到,position="dodge" 的部分不起作用(Ta)。 Width=0,5 仅用于可见性。

重塑是关键。由于您有两个几何条形结构,因此它们都放置在相同的位置。使用重塑可以让您获得预期的输出:

library(ggplot2)
library(dplyr)
library(tidyr)
#Code
Mischbewuchs %>% select(c(Variable,day,night)) %>%
  pivot_longer(-1) %>%
  ggplot(aes(x=Variable,y=value,fill=name))+
  geom_bar(stat = "identity", width = 0.5, position = "dodge")+
  labs(y= "Spearman rank correlation coefficient", title = "a)")+
  geom_abline(intercept = 0, slope = 0, color="black")+
  theme_bw()+
  scale_fill_manual(values = c('orange','blue'))

输出: