使用ggplot2在R中组合堆叠条形图和折线图的问题

时间:2020-05-20 01:52:29

标签: r ggplot2

library(ggplot2)
library(reshape2)

data <- data.frame(partition = c("1", "2", "3", "4","5"), 
edge=c(2914.2025,4274.438333,7072.29,7984.68,10232.96333), 
cloud=c(11445.02,10384.94,9165.71,7884.15,7113.79),
communication=c(803345.0248,805614.764,810357.3823,460484.3287,483277.6666))
df2 <- data.frame(partition = c("1", "2", "3", "4","5"),output_data=c(199.1,199.1,199.1,99.5,99.5))
elections_long <- melt(data, id = "partition")
ggplot(elections_long, aes(x = partition, y = value)) +
geom_bar(stat="identity", aes(fill = variable))+geom_line(data=df2, aes(x=partition, y=value), 
colour="blue")

在R中绘制图形(如下面的堆叠条形图所示的图形)时,我遇到了一些问题。

enter image description here

边缘,云和通信以堆叠的条形表示,而输出数据应以线形图表示。

1 个答案:

答案 0 :(得分:0)

您可以使用df2中的数据获取长格式的数据,创建堆叠的条形图,并在其上添加一条线。

library(ggplot2)

tidyr::pivot_longer(data, cols = -partition) %>%
   ggplot() + aes(x = partition, y = value) +
   geom_col(aes(fill = name)) +
   geom_line(data=df2, aes(x=partition, y=output_data, group = 1), colour="blue")