【问题标题】:combine ggplots from dataframes with different lengths结合不同长度的数据帧中的ggplots
【发布时间】:2021-07-13 03:52:55
【问题描述】:

我有两个来自不同长度的数据帧的 ggplots,我分别绘制了一列的直方图,如下所示。我想将这两个图组合成一个具有两个不同 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)

【问题讨论】:

  • 没有时间研究示例。查看r-graph-gallery.com/line-chart-dual-Y-axis-ggplot2.html。请注意,虽然可行,但请考虑将 2 个图表并排放置是否能以更好的方式传达您的信息。
  • 把你的数据变成长格式,然后刻面你想比较的图。如果您可以为两个数据框添加一些示例数据,这将有助于测试和验证解决方案。使用dput(your_dataframe) 将您的数据粘贴到问题中minimal reproducible example 提供了一些关于提出好问题的提示。

标签: r ggplot2 plot histogram density-plot


【解决方案1】:

我们没有你的数据,所以这里有一个包含在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 中辅助轴的工作方式;您首先将数据缩放到主轴上,然后创建辅助轴作为帮助读者理解它的注释。)

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"))

【讨论】:

  • “我只想知道我的数据中有多少属于直方图等数字范围内。”这是一个模糊的问题,如果没有更多解释,将很难回答。另外,我从你的汇总统计列表中无法理解——我们应该从中看到什么?
  • 对不起。请忽略我刚才说的话。我被误解了。
猜你喜欢
  • 2012-12-15
  • 1970-01-01
  • 2020-04-10
  • 2019-02-27
  • 2023-03-16
  • 2016-11-03
  • 2020-01-11
  • 2015-07-25
  • 1970-01-01
相关资源
最近更新 更多