首页 > 解决方案 > 在 geom_bar 上绘制一条线

问题描述

我正在尝试在我的条形图上绘制一条线,该条形图显示 Import + Export。有人可以帮忙吗?在 geom_line 之前一切正常。这个网站启发了我这样做https://aledemogr.com/2017/05/29/plots-based-on-un-data-in-r/,但似乎无法做到这一点......

library(tidyverse)
library(readxl)

eximp <- read_excel("C:/Users/xxx/Downloads/eximp.xlsx")


mydata <- eximp %>% mutate(Balance=Export+Import) %>% 
  gather(Type,value,-1,-4)
base <- mydata %>%
  filter(Type != "Balance")

balance <- mydata %>%
  filter(Type == "Balance")

ggplot(balance, aes(x = Date, y = value)) +
  geom_bar(data = base, aes(fill = Type), stat = "identity") +
  geom_point(aes(colour = Type)) +
  geom_line(aes(colour = Type, group=1)) +
  labs(x = "", y = "Trade")+
  theme_classic()

.

Error: Aesthetics must be either length 1 or the same as the data (1): colour, x and y

数据:

eximp
# A tibble: 10 x 3
   Date                Export Import
   <dttm>               <dbl>  <dbl>
 1 2020-03-01 00:00:00 1000.   -804.
 2 2020-04-01 00:00:00 1212.  -2011.
 3 2020-05-01 00:00:00  806.  -1504.
 4 2020-06-01 00:00:00  700.   -320.
 5 2020-07-01 00:00:00  689.   -650.
 6 2020-08-01 00:00:00  260.  -1423.
 7 2020-09-01 00:00:00  371.   -512.
 8 2020-10-01 00:00:00  390.   -800.
 9 2020-11-01 00:00:00  235.  -1402.
10 2020-12-01 00:00:00   98.2  -662.



> dput(eximp)
structure(list(Date = structure(c(1583020800, 1585699200, 1588291200, 
1590969600, 1593561600, 1596240000, 1598918400, 1601510400, 1604188800, 
1606780800), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
    Export = c(1000.49219126285, 1211.52108001295, 805.787086089857, 
    699.544263919341, 689.023877568315, 260.324542543, 370.641681212495, 
    390.499682375661, 234.51939579408, 98.1534745), Import = 
c(-803.910230262846, 
    -2011.04895501295, -1504.48058508986, -320.103174919341, 
    -650.005315568315, -1423.04591701548, -511.837273212495, 
    -800.04198337566, -1401.98263179408, -661.847163189375)), row.names = 
c(NA, 
-10L), class = c("tbl_df", "tbl", "data.frame"))

标签: r

解决方案


这几乎与@Brian Fisher 的回答一样,但使用了更新的pivot_longer()功能并适用于一个修改后的数据集。

library(dplyr)
library(tidyr)
library(ggplot2)


mydata <- 
  eximp %>% 
  mutate(Balance = Export+Import) %>% 
  pivot_longer(-Date)


ggplot() +
  geom_col(data = filter(mydata, name != "Balance"), aes(Date, value, fill = name))+
  geom_line(data = filter(mydata, name == "Balance"), aes(Date, value), size = 1) +
  labs(x = NULL,
       y = "Trade",
       fill = "Type")+
  theme_classic()

reprex 包于 2021-03-29 创建(v1.0.0)


推荐阅读