### R之上的年份之間的趨勢

#### [英]Trend between years on top of bar R

I am trying to create a bar chart in R that shows data for two years at the same time. I want the top of each bar to show the slope between both years (and if possible include an arrow).

It is easier to show an image of it. I have been able to do it in quite a fiddly way in Excel: Excel chart

This could be an example dataset:

``````cat <- c("Item1", "Item2", "Item3")
year1 <- c(20,40,10)
year2 <- c(30,30,10)
data <- cbind(cat, year1, year2)
``````

Anyone has any idea of how this could be done?

Thank you!

## 2 个解决方案

### #1

1

You can do a lot with `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("")
``````

### #2

1

I would agree with the comment given by Andrew.

If you want the plot, you could go the manual way with `plot()` and `polygon()` like so

``````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)
}
`````` #### 注意！

© 2014-2021 ITdaan.com