我想创建一个时间序列图,以显示两个变量如何随时间变化并将它们着色为适当的区域?
我有2个地区,英格兰和威尔士,每个地区都计算了total_tax和total_income。
我想使用years变量将它们绘制在ggplot
上。
我该怎么做并分别为区域着色?
我有一个将在x轴上放置的Year变量,然后我想在图形上同时绘制incometax
和taxpaid
,但要显示它们随时间的变化?
如何添加第3轴以获取这两个变量随时间变化的图?
我已经尝试过这段代码,但是它没有按照我想要的方式工作。
ggplot(tax_data, filter %>% aes(x=date)) +
geom_line(aes(y=incometax, color=region)) +
geom_line(aes(y=taxpaid, color=region))+
答案 0 :(得分:1)
ggplot在开始时有点难以掌握-我猜您正在尝试实现以下目标:
假设您的数据采用的格式是每个日期,所得税和已纳税的列-我在这里创建一个示例:
library(tidyverse)
dataset <- tibble(date = seq(from = as.Date("2015-01-01"), to = as.Date("2019-12-31"), by = "month"),
incometax = rnorm(60, 100, 10),
taxpaid = rnorm(60, 60, 5))
现在,要为每个incometax
和taxpaid
绘制一条线,我们需要对数据(see here for details)进行整形或“整理”:
dataset <- dataset %>% pivot_longer(cols = c(incometax, taxpaid))
现在您有3列这样的内容-我们已将之前的列名称转换为变量name
:
# A tibble: 6 x 3
date name value
<date> <chr> <dbl>
1 2015-01-01 incometax 106.
2 2015-01-01 taxpaid 56.9
3 2015-02-01 incometax 112.
4 2015-02-01 taxpaid 65.0
5 2015-03-01 incometax 95.8
6 2015-03-01 taxpaid 64.6
现在ggplot
的格式正确,您可以将name
映射到线条的颜色:
ggplot(dataset, aes(x = date, y = value, colour = name)) + geom_line()