【问题标题】:ggplot with two x variables具有两个 x 变量的 ggplot
【发布时间】:2018-08-29 23:09:50
【问题描述】:

我正在尝试在 ggplot 中绘制 Current_Prices 和 Test_Prices,例如 fill,但在 dplyr 中运行汇总后,我无法弄清楚合并这两列的函数。

carrier%>%
  group_by(!!category) %>%
  summarise(Current_Prices = mean(original_percent_higher[original_percent_higher>0], na.rm = TRUE), 
            Test_Prices = mean(Percent_Higher[Percent_Higher>0], na.rm = TRUE)) %>%
  ggplot(aes_string(input$Category, "Current_Prices")) + 
  geom_bar(stat = "identity", position = "dodge", na.rm = TRUE) + 
  geom_text(aes(label = scales::percent(Current_Prices)), size = 3.2, vjust = -0.5, 
            position = position_dodge(width = 1), na.rm = TRUE)

我想在 summarise 和 ggplot 之间创建类似于:

Class Version Mean
a     current  1
a     test     2
b     current  3
b     test     4 

然后我可以运行 ggplot,其中 Class 作为 x,Mean 作为 y,Version 作为填充。

总结后我现在拥有的是这样的:

Class Current Test
a     1       2
b     3       4
c     5       6

【问题讨论】:

  • 请展示一个小的可重复的初始数据示例

标签: r ggplot2


【解决方案1】:

目前,这些值采用“宽”格式,对于 ggplot,您希望它们采用“长”格式,如您所说。下面将把你描述的summary的输出转换成你想要的格式。 data_wide 的创建仅用于本示例的说明目的。当然,您也可以使用管道 (%>%) 运算符将其插入到现有语句中:

library(tidyr)

data_wide <- data.frame(Class = c('a', 'b', 'c'),
                        Current = c(1, 3, 5),
                        Test = c(2, 4, 6))

data_long <- gather(data_wide, Version, Mean, Current:Test, factor_key=TRUE)

【讨论】:

    【解决方案2】:

    DMR's answer 指向正确的方向,但不完整,因为它遗漏了绘图部分。

    library(tidyr)
    library(ggplot2)
    data.frame(Class = c('a', 'b', 'c'),
               Current = c(1, 3, 5),
               Test = c(2, 4, 6)) %>% 
      # reshape from wide to long format
      gather(Version, Mean_Price, -Class) %>%
      # here comes the plotting stuff 
      ggplot(aes(Class, Mean_Price, fill = Version)) +
      geom_bar(stat = "identity", position = "dodge", na.rm = TRUE) +
      geom_text(aes(label = scales::percent(Mean_Price)), size = 3.2, vjust = -0.5,
                position = position_dodge(width = 1), na.rm = TRUE)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2015-04-23
      • 1970-01-01
      • 2023-03-08
      • 2018-11-18
      相关资源
      最近更新 更多