首页 > 解决方案 > 从数据框中获取多个值以进行复杂的 ggplot/dotplot

问题描述

我有这个数据框。 在此处输入图像描述

我想做类似的事情:

在此处输入图像描述

到目前为止,我所做的只是使用一列来反对(Q1)反对性(Genul)。但我想在情节中包含每个问题/列。

这是我的代码:

ggplot(df3, aes(x = Q1, y = 1, colour = Genul)) +
  geom_point() +
  geom_hline(aes(yintercept = 1), linetype = "dotted") 

在此处输入图像描述

标签: rggplot2

解决方案


我认为您的评论 “您为什么要这样做?”总结了这个问题中的基本“问题”。. 通过这一切,ggplot2当数据是长格式副宽时,可以做更多(更容易)。有了这个,我建议你阅读ggplot:为什么我必须将数据转换为长格式?,它提供了两个答案来解决这个问题。

为了结束您关于如何复制该图片的问题,这里有一些随机数据和一个图表,可以让您沿着路径走得更远。

questions <- data.frame(
  qnum = c("Q1", "Q2", "Q3"),
  qtxt = c("More intense room cleaning", "Conduct COVID-19 rapid tests",
           "Additional cleaning")
)

set.seed(42)
responses <- cbind(
  data.frame(Genul = c("Feminin", "Masculin")),
  sapply(c("Q1", "Q2", "Q3"),
         function(ign) runif(n = 2, min = 0, max = 50),
         simplify = FALSE)
)

responses
#      Genul       Q1       Q2       Q3
# 1  Feminin 45.74030 14.30698 32.08728
# 2 Masculin 46.85377 41.52238 25.95480

重塑后的数据如下所示:

library(dplyr)
library(tidyr) # pivot_longer
pivot_longer(responses, -Genul, names_to = "qnum")
# # A tibble: 6 x 3
#   Genul    qnum  value
#   <chr>    <chr> <dbl>
# 1 Feminin  Q1     45.7
# 2 Feminin  Q2     14.3
# 3 Feminin  Q3     32.1
# 4 Masculin Q1     46.9
# 5 Masculin Q2     41.5
# 6 Masculin Q3     26.0

这是情节:

library(ggplot2)
responses %>%
  pivot_longer(-Genul, names_to = "qnum") %>%
  left_join(questions, by = "qnum") %>%
  ggplot(aes(value, qtxt)) +
  geom_point(aes(color = Genul)) +
  labs(x = NULL, y = NULL) +
  scale_x_continuous(limits = c(0, 50))

示例 ggplot

您的代码中似乎没有一些主题更改,我相信他们会干净地应用于这种方法。您的问题可能需要进行一些调整以更清晰地适应它们;为此,我建议可能将strwrap和组合在一起paste(.., collapse="\n")......一个不同的问题,根据您的实际数据可能没有必要。

(另一个注意事项:您可能需要factor在您的问题上使用 s 以确保它们的排序正确。这种分解应该可能发生在我的questions框架中,排序在qnum.)


推荐阅读