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).

我正在嘗試在R中創建一個條形圖,同時顯示兩年的數據。我希望每個柱的頂部顯示兩年之間的斜率(如果可能的話,還包括箭頭)。

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

顯示它的圖像更容易。我已經能夠在Excel中以相當繁瑣的方式完成它:Excel圖表

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

你可以用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

如果你想要繪圖,你可以使用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)
}

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2017/07/13/721184e0ac5637e35bdee6517bd46809.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com