r - 在 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"))
解决方案
这几乎与@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)
推荐阅读
- java - NotificationManagerCompat 中的 (android.content.Context) 无法应用于
- c - 在具有库的目标主机上开发 Paho-Mqtt-C 应用程序
- azure-active-directory - Azure AD 中 auth\access 令牌请求的限制
- html - Flask 表单不允许我上传 TSV 文件
- python - 图像未显示在 tkinter 画布上
- mysql - 如何在 mysql 和“全有或全无”模式下执行 N 次插入
- swift - Xcode 不接收 pod 更新
- algorithm - 基数排序是复杂性算法 P 还是 NP 的一个例子?
- android-studio - Android Studio Editor 3.4.1 中的类名称未着色
- firebase - 使用 CollectionGroupQuery 的子集合中的 Firestore 写入限制