我试图在ggplot中绘制fill
之类的Current_Prices和Test_Prices,但是在dplyr中运行summary之后,我无法弄清楚将这两列合并的函数。
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)
我想在Summary和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
答案 0 :(得分:0)
当前,这些值采用“宽”格式,对于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)
答案 1 :(得分:-1)
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)