结合来自不同长度的数据帧的ggplots

combine ggplots from dataframes with different lengths

我有两个来自不同长度数据帧的 ggplot,我已经分别绘制了一列的直方图,如下所示。我想将这两个图组合成一个具有两个不同 y 轴的 ggplot,一个在右边,一个在左边,用于两个数据框。我该怎么做?

a = ggplot(GG, aes(x = as.numeric(Kstat))) +
  theme_pubclean()

a + geom_density() +
  geom_vline(aes(xintercept = mean(Kstat)), 
             linetype = "dashed", size = 0.6) + xlim(0,1000)+ylim(0,0.1)

b = ggplot(all, aes(x = as.numeric(Kstat))) +
  theme_pubclean()

b + geom_density() +
  geom_vline(aes(xintercept = mean(Kstat)), 
             linetype = "dashed", size = 0.6) + xlim(0,1000)+ylim(0,0.5)

我们没有您的数据,所以这里有一个数据集包含在 ggplot2 中的示例:

library(ggplot2)
df1 <- diamonds[1:10,7]
df2 <- diamonds[100:2100,7]

对于这个例子,df1 中的数据变化小得多,因此密度峰值高约 25 倍。

ggplot() +
  geom_density(data = df1, aes(x = price)) +
  geom_vline(data = df1, aes(xintercept = mean(price)), 
             linetype = "dashed", size = 0.6) +
  geom_density(data = df2, aes(x = price), color = "red") +
  geom_vline(data = df2, aes(xintercept = mean(price)), 
             linetype = "dashed", color = "red", size = 0.6) 

解决这个问题的一种方法是将 df2 密度放大 25 倍,并创建一个具有反向调整的辅助轴。 (这就是 ggplot2 中辅助轴的工作方式;您首先将数据缩放到主轴中,然后创建一个辅助轴作为帮助 reader 解释它的注释。)

ggplot() +
  geom_density(data = df1, aes(x = price)) +
  geom_vline(data = df1, aes(xintercept = mean(price)), 
             linetype = "dashed", size = 0.6) +
  geom_density(data = df2, aes(x = price, y = ..density.. * 25), color = "red") +
  geom_vline(data = df2, aes(xintercept = mean(price)), 
             linetype = "dashed", color = "red", size = 0.6) +
  scale_y_continuous(sec.axis = ~ . / 25) +
  theme(axis.text.y.right = element_text(color = "red"))