【问题标题】:Plotting differences with ggplot2用 ggplot2 绘制差异
【发布时间】:2017-04-17 13:58:13
【问题描述】:

我有一个像这样的 R 数据框(名为 frequency):

word    author  proportion
a   Radicals    1.679437e-04
aa  Radicals    2.099297e-04
aaa Radicals    2.099297e-05
abbe    Radicals    NA
aboow   Radicals    NA
about   Radicals    NA
abraos  Radicals    NA
ytterst Conservatives   5.581042e-06
yttersta    Conservatives   5.581042e-06
yttra   Conservatives   2.232417e-05
yttrandefrihet  Conservatives   5.581042e-06
yttrar  Conservatives   2.232417e-05

我想使用 ggplot2 绘制文档差异。类似this

我有下面的代码,但我的情节最终是空的。

library(scales)
ggplot(frequency, aes(x = proportion, y = `Radicals`, color = abs(`Radicals` - proportion))) +
    geom_abline(color = "gray40", lty = 2) +
    geom_jitter(alpha = 0.1, size = 2.5, width = 0.3, height = 0.3) +
    geom_text(aes(label = word), check_overlap = TRUE, vjust = 1.5) +
  scale_x_log10(labels = percent_format()) +
  scale_y_log10(labels = percent_format()) +
  scale_color_gradient(limits = c(0, 0.001), low = "darkslategray4", high = "gray75") +
  facet_wrap(~author, ncol = 2) +
  theme(legend.position="none") +
  labs(y = "Radicals", x = NULL)

【问题讨论】:

  • y = Radicals 方法不正确。

标签: r plot ggplot2 tidyverse tidytext


【解决方案1】:

您的情节最终是空的,因为没有“激进分子”一列。如果你试图缩小到只有激进分子然后绘制你应该做类似的事情

 radical_frequecy <- subset(frequency, author == 'Radicals')

那你就可以了

 library(scales)
 ggplot(radical_frequency, aes(x = proportion, y = author, color = abs(`Radicals` - proportion))) +
geom_abline(color = "gray40", lty = 2) +
geom_jitter(alpha = 0.1, size = 2.5, width = 0.3, height = 0.3) +
geom_text(aes(label = word), check_overlap = TRUE, vjust = 1.5) +
   scale_x_log10(labels = percent_format()) +
   scale_y_log10(labels = percent_format()) +
   scale_color_gradient(limits = c(0, 0.001), low = "darkslategray4", high = "gray75") +
   theme(legend.position="none") +
   labs(y = "Radicals", x = NULL)

(我取出了 facet wrap,因为你已经缩小到 Radicals。你可以把它加回去,如果你做了 y=author 和 facet_wrap(~author , ncol = 2)

基本上,tl:dr 您的错误是由于尝试从变量而不是列创建轴引起的

【讨论】:

  • 还是同样的问题。我尝试按照Figure 1.3 here 的教程进行操作
  • 好的,再次,看起来您错过了他们在顶部创建变异数据框的核心步骤。我想你可以回去试试这些步骤。
  • 那么您的频率表没有反映这一点。该示例的输出将为那里的每个作者提供一列。你的没有。查看 ggplot 如何处理这些绘图,您将能够更好地制作这些图表。有很多很棒的教程,例如this one
【解决方案2】:

如果您想要做的是比较 x 轴上一位“作者”(例如,保守派)和 y 轴上一位“作者”(可能是激进派)的频率的图,您需要 spread 您的数据框(来自 tidyr 包),以便您可以这样绘制它。

library(tidyverse)
library(scales)

frequency %>%
  spread(author, proportion) %>%
  ggplot(aes(Conservatives, Radicals)) +
  geom_abline(color = "gray40", lty = 2) +
  geom_point() + 
  geom_text(aes(label = word), check_overlap = TRUE, vjust = 1.5) +
  scale_x_log10(labels = percent_format()) +
  scale_y_log10(labels = percent_format())

【讨论】:

  • 谢谢!我能够像this 一样解决它。这看起来合理吗?
  • 是的,看起来像;你可能会考虑下次试试spread()
猜你喜欢
  • 2019-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-07
  • 2021-02-21
  • 1970-01-01
  • 2020-12-02
  • 1970-01-01
相关资源
最近更新 更多