我正在尝试在R中创建一个条形图,同时显示两年的数据。我希望每个栏的顶部显示两年之间的斜率(如果可能的话,还包括箭头)。
显示图像更容易。我已经能够在Excel中以相当繁琐的方式完成它:Excel chart
这可能是一个示例数据集:
cat <- c("Item1", "Item2", "Item3")
year1 <- c(20,40,10)
year2 <- c(30,30,10)
data <- cbind(cat, year1, year2)
任何人都知道如何做到这一点?
谢谢!
答案 0 :(得分:1)
我同意安德鲁的评论。
如果你想要这个情节,你可以手动使用plot()
和polygon()
这样
y <- cbind(0,year1,year2,0)
x <- 2015 + cbind(1:3-.3, 1:3-.3, 1:3+.3, 1:3+.3)
plot(-1,-1,xlim = 2015 + c(0,4), ylim = c(0,100))
for(i in 1:3){
polygon(x[i,], y[i,], col = 3)
}
答案 1 :(得分:1)
您可以使用ggplot2
library(tidyverse)
library(reshape2)
cat <- factor(c("Item1", "Item2", "Item3"))
year1 <- c(20,40,10)
year2 <- c(30,30,10)
data <- data.frame(cat, year1, year2)
head(data)
data2 <- melt(data, c("cat"))
data2 <- data2[order(data2$cat), ]
data2$id2 <- 1:nrow(data2)
ggplot(data2, aes(id2, value, group = factor(cat))) +
geom_area(fill = "lightblue") +
geom_path(arrow = arrow()) +
scale_x_continuous(breaks = c(1.5, 3.5, 5.5), labels = cat) +
xlab("") + ylab("")